I previously asked a similar question here 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>
Thanks for any and all help!
Ember Model just does ClassType.create()
to create instances, it doesn't use the container for instantiating instances. This means, no DI with Ember Model. You could attach the container to a base Ember Model, have all of your model's inherit from it, and then attach the appConfig to it.
MODEL_FACTORY_INJECTIONS applies to Ember Data.
Generally I'd avoid recommending hitting the container raw like, but people do what they want to do, so here's how it could be done.
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()
});