Anshul
Anshul

Reputation: 9480

dependency injection in context of backbone.js

I heard a lot about dependency injection(DI) in angular js. how we can achieve the same in backbone.js. I am browsing for the same but all articles are using requirejs for DI in backbone. How backbone is doing DI or How we can achieve DI in backbone ?

Upvotes: 1

Views: 2434

Answers (2)

Vikram
Vikram

Reputation: 4192

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.

Upvotes: 1

CharlieBrown
CharlieBrown

Reputation: 4163

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.js
define(function(require, exports, module){
  var Backbone = require("backbone"); //shimmed in requirejs config
  module.exports = Backbone.Model.extend({
    defaults: {
      name: "Silly Model"
    } 
  });
});

//in another file
define(function(require, exports, module){
  var Backbone = 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!

Upvotes: 1

Related Questions