dependency injection in context of backbone.js

扶醉桌前 提交于 2019-12-11 06:45:41

问题


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 ?


回答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.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!




回答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.



来源:https://stackoverflow.com/questions/25786927/dependency-injection-in-context-of-backbone-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!