ebryn / ember-model

A lightweight model library for Ember.js
MIT License
524 stars 159 forks source link

Dependency injection #379

Closed smithcommajoseph closed 10 years ago

smithcommajoseph commented 10 years ago

I previously asked a similar question on Stack Overflow Injecting dependencies into an Ember model, but I now believe my issue is really around injection of dependencies into an 'ember-model' model.

Even when I have set Ember.MODEL_FACTORY_INJECTIONS = true, I cannot seem to inject deps into my models that are constructed with Ember.Model.

I have created a jsbin http://emberjs.jsbin.com/yizoyozu/4/edit?html,js,console,output which demonstrates injection working for routes, views, and controllers, but not for models.

the code is something akin to:

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

with the following templates

  <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>

Is this not supported by ember-model or am I misunderstanding how to use this feature?

smithcommajoseph commented 10 years ago

got my answer here http://stackoverflow.com/questions/24133529/injecting-dependencies-into-an-ember-model-model-and-use-of-the-model-factory

in short yes, this is not supported by ember-model at this time yes, I was misunderstanding how to use this feature yes, there is still a way to handle dependency injection in ember-model models (outlined in the above SO answer)