Our shop just recently adopted Backbone, and even gave me the green light to try out Marionette. However the latter is not giving me the bang for the buck I'd hoped for (possibly due to my ignorance), so instead I'm trying to devise a lightweight dependency injection system where all my Backbone views get an instance of an "Application" object of my own devising.
My system is based on a (necro) answer I posted yesterday and below is code that is working for me. However I don't want to have duplicate blocks of code for each view inside the injectViewsWithApp
function, but rather would like to just loop over the views. But this is where I can't figure out how to get things working inside the loop, I think it's some sort of scoping issue.
I will continue working on it so I may post updates to the code during my remaining hour before my weekend begins.
define(['backbone', './app/views/searchform', './app/views/searchresults', './app/views/FooBardetailrow'],
function(Backbone, SearchFormView, SearchResultsView, FooBarDetailRowView) {
var APP = initApp();
injectViewsWithApp();
launchApp();
function initApp() {
return {
collections : { // No need for separate files/modules if each view gets injected with the APP
extendedHaulFooBars : new (Backbone.Collection.extend({})),
stn333sts : new (Backbone.Collection.extend({})),
FooBarTypes : new (Backbone.Collection.extend({})),
FooBarSymbols : new (Backbone.Collection.extend({})),
FooBarSearchParams : new (Backbone.Collection.extend({}))
},
defaultModel : Backbone.Model.extend({}),
views : {}
};
}
function injectViewsWithApp() {
SearchFormView.instantiator = SearchFormView.extend({
initialize : function() {
this.app = APP;
SearchFormView.prototype.initialize.apply(this, arguments);
}
});
SearchResultsView.instantiator = SearchResultsView.extend({
initialize : function() {
this.app = APP;
SearchResultsView.prototype.initialize.apply(this, arguments);
}
});
FooBarDetailRowView.instantiator = FooBarDetailRowView.extend({
initialize : function() {
this.app = APP;
FooBarDetailRowView.prototype.initialize.apply(this, arguments);
}
});
}