【问题标题】:Injecting dependencies into an 'ember-model' Model and use of the MODEL_FACTORY_INJECTIONS flag将依赖项注入“ember-model”模型并使用 MODEL_FACTORY_INJECTIONS 标志
【发布时间】:2014-06-10 05:31:30
【问题描述】:

我之前在这里Injecting dependencies into an Ember model 提出了类似的问题,但我现在认为我的问题实际上是关于将依赖项注入“ember-model”模型。

即使我设置了 Ember.MODEL_FACTORY_INJECTIONS = true,我似乎也无法将 deps 注入到使用 Ember.Model 构建的模型中。

我创建了一个 jsbin http://emberjs.jsbin.com/yizoyozu/4/edit?html,js,console,output,它演示了注入适用于路由、视图和控制器,但不适用于模型。

代码类似于:

Ember.MODEL_FACTORY_INJECTIONS = true;

App = Ember.Application.create();

App.initializer({
  name: 'config',
  initialize: function(container) {
    App.deferReadiness();
    container.register('app:config', {foo: 'bar', baz: 'boom'}, {instantiate: false});
    container.injection('model', 'appConfig', 'app:config');
    container.injection('controller', 'appConfig', 'app:config');
    container.injection('route', 'appConfig', 'app:config');
    container.injection('view', 'appConfig', 'app:config');
    App.advanceReadiness();
  }
});

App.Router.map(function() {
  // put your routes here
});

App.Colors = Ember.Model.extend({
  color: Ember.attr(),
  init: function() {
    this._super();
    console.log('inside aModel', this.appConfig); // does this not work?
  }
});

App.Colors.load([
  {id: 1, color: 'red'}
]);

App.IndexRoute = Ember.Route.extend({
  model: function() {
    console.log('inside aRoute', this.appConfig);
    return App.Colors.find(1);
  }
});

App.IndexController = Ember.Controller.extend({
  init: function() {
    this._super();
    console.log('inside aController', this.appConfig);
  }
});

使用以下模板

  <script type="text/x-handlebars">
    <h2> Welcome to Ember.js</h2>

    {{outlet}}
  </script>

  <script type="text/x-handlebars" data-template-name="index">
    <ul>

      <li>model.color = {{model.color}}</li>
      <li>model.appConfig =  {{model.appConfig}}</li> <!-- I won't print model.appConfig -->
      <li>view.appConfig.foo = {{appConfig.foo}}</li>

    </ul>
  </script>

感谢您的所有帮助!

【问题讨论】:

    标签: ember.js ember-model


    【解决方案1】:

    Ember Model 只是使用ClassType.create() 创建实例,它不使用容器来实例化实例。这意味着,Ember 模型没有 DI。您可以将容器附加到基础 Ember 模型,让您的所有模型都继承自它,然后将 appConfig 附加到它。

    MODEL_FACTORY_INJECTIONS 适用于 Ember 数据。

    一般情况下,我会避免建议像直接点击容器一样,但人们会做他们想做的事,所以这里是可以做到的。

    App.BaseModel = Ember.Model.extend({
      appConfig: function(){
        return App.__container__.lookup('app:config');
      }.property()
    });
    
    App.Cow = App.BaseModel.extend({
      id: Ember.attr(),
      name: Ember.attr()
    });
    

    http://jsbin.com/fojacoxe/1/edit

    【讨论】:

    • 我喜欢您推荐的方法。但是如何将应用程序的容器附加到 Ember.Model 上呢?我看到您可以使用App.buildContainer() 获取Application 容器,这似乎将引用返回给App.__container__,但之后我不知所措。
    • 明白了,我把整个事情复杂化了。谢谢!
    猜你喜欢
    • 2014-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-29
    • 1970-01-01
    • 2011-01-04
    相关资源
    最近更新 更多