ken
ken

Reputation: 9013

Injecting session into a model

I'd like to be able to inject my Session singleton into my Ember models. The use case I'm trying to support is having computed properties on the model that react to the user's profile (a property on the Session object).

App = window.App = Ember.Application.create({
    ready: function() {
       console.log('App ready');
       this.register('session:current', App.Session, {singleton: true});
       this.inject('session:current','store','store:main');
       this.inject('controller','session','session:current');
       this.inject('model','session','session:current');
    }
});

The injection works fine into the controller but I'm having trouble with getting it to the model. Is there any limitation here? Any special techniques?

-------- Additional Context ---------

Here's an example of what I'd like to be able to do in my model definition:

App.Product = DS.Model.extend({
    name: DS.attr("string"),
    company: DS.attr("string"),
    categories: DS.attr("raw"),
    description: DS.attr("string"),

    isConfigured: function() {
        return this.session.currentUser.configuredProducts.contains(this.get('id'));
    }.property('id')
}); 

Upvotes: 0

Views: 1899

Answers (1)

Marcio Junior
Marcio Junior

Reputation: 19128

By default injections in models don't work. To do so you need to set the flag Ember.MODEL_FACTORY_INJECTIONS = true:

Ember.MODEL_FACTORY_INJECTIONS = true;

App = window.App = Ember.Application.create({
    ready: function() {
       console.log('App ready');
       this.register('session:current', App.Session, {singleton: true});
       this.inject('session:current','store','store:main');
       this.inject('controller','session','session:current');
       this.inject('model','session','session:current');
    }
});

The downside of this, is that it create some break changes:

  • If you have App.Product.FIXTURES = [...] you neeed to use App.Product.reopenClass({ FIXTURES: [...] });

  • productRecord.constructor === App.Product will evaluate to false. To solve this you can use App.Product.detect(productRecord.constructor).

Upvotes: 11

Related Questions