依赖注入在Backbone.js的上下文 [英] dependency injection in context of backbone.js

查看:138
本文介绍了依赖注入在Backbone.js的上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听到了很多关于JS角度依赖注入(DI)。我们如何能够实现Backbone.js的一样。我在浏览相同,但所有的文章都在使用主干 requirejs 的DI。如何骨干做DI或我们如何能够实现骨干DI?

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 ?

推荐答案

骨干还没有DI的概念包含进去。它是一个多框架的库。通常像requirejs或browserify工具会做的关系是不注射给你。

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.

我preFER它的味道CommonJS的,叫要求(模块)只要你需要它,就像这样:

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
  });
});

当然,这不是真正 DI当你在Java或.NET与接口,但是你也可以使用需要真正能够提供动态的依赖时,工厂模式。

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.

您也可以拨打要求(XXX)而不是 SillyModel

module.exports = Backbone.Collection({
  model: require("models/dependency1")
});

我preFER有依赖关系的总结在顶部,它简化理解一下这个文件是什么。 :)

I prefer to have the summary of dependencies at the top, it simplifies understanding what this file is about. :)

希望它帮助!

这篇关于依赖注入在Backbone.js的上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆