Dependency Injection In Context Of Backbone.js
Solution 1:
Backbone has not the concept of DI included into it. It's more a library than a framework. Normally tools like requirejs or browserify will do the dependecy injection for you.
I prefer the CommonJS flavor of it, calling require("module")
whenever you need it, like this:
//in file models/dependency1.jsdefine(function(require, exports, module){
varBackbone = require("backbone"); //shimmed in requirejs configmodule.exports = Backbone.Model.extend({
defaults: {
name: "Silly Model"
}
});
});
//in another filedefine(function(require, exports, module){
varBackbone = require("backbone"),
SillyModel = require("models/dependency1");
module.exports = Backbone.Collection.extend({
model: SillyModel
});
});
Of course this not real DI as you get in Java or .NET with interfaces, but you can also use a factory pattern when needed to really be able to provide the dependency dynamically.
You can also call require(XXX)
instead of SillyModel
:
module.exports = Backbone.Collection({
model: require("models/dependency1")
});
I prefer to have the summary of dependencies at the top, it simplifies understanding what this file is about. :)
Hope it helps!
Solution 2:
cujo.js/wire will provide you architectural toolset to use DI in JS. It also bundles a lot of other goodies ( Promise, Polyfill, AOP,DOM handling etc.)
It allows you to declaratively create components and connect these components, inject references into your components. github wiki page
Here is a link to Github repo that demonstrates using cujo.js/wire
and backbone.js
side by side.
Post a Comment for "Dependency Injection In Context Of Backbone.js"