Injecting dependencies into an Ember model

独自空忆成欢 提交于 2019-12-20 03:44:09

问题


I'm attempting to inject dependencies into my Ember models.

https://github.com/emberjs/ember.js/issues/3670, states that this is disabled. Following a link to https://github.com/stefanpenner/ember-cli/blob/master/blueprint/app/app.js#L4 demonstrates how to enable MODEL_FACTORY_INJECTIONS, which in theory, should allow me to inject dependencies into my models, however I'm having no luck.

In the absence of this solution, are there other ways to inject a ref to an app-wide, global singleton object into an Ember.Model besides just dumping it onto the app's namespace (ie. App.ImAGlobalconfig`)?

for reference, this is the initializer I'm working on

App.initializer({
  name: 'preload',
  initialize: function(container/*, application*/) {
    App.deferReadiness();

    Ember.$.ajax({
      url: CONFIG.configURL,
      dataType: 'json',
      context: this
    }).done(
      function(json/*,status, request*/) {
       var appConfig;

        // ...

        container.register('app:config', appConfig, {instantiate: false});
        container.injection('controller', 'appConfig', 'app:config');
        container.injection('route', 'appConfig', 'app:config');
        container.injection('view', 'appConfig', 'app:config');
        container.injection('model', 'appConfig', 'app:config'); // I don't work!

        App.advanceReadiness();
      }
    ).fail(
      function(status, request, error) {
        console.log('Unable to load config with: ' + error);
      }
    );
  }
});

Thanks for any and all help/opinions.


回答1:


Model injections does indeed work:

Ember.MODEL_FACTORY_INJECTIONS = true;    
App = Ember.Application.create();

App.initializer({
  name: 'model-injection',

  initialize: function(container, application) {

    var cfg = {version: '1'};
    container.register('app:config', cfg, {instantiate: false});


    container.injection('model', 'cfg', 'app:config');
    App.advanceReadiness();
  }
});

App.deferReadiness();

http://emberjs.jsbin.com/lomiy/1/edit



来源:https://stackoverflow.com/questions/24068890/injecting-dependencies-into-an-ember-model

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