Injecting session into a model

試著忘記壹切 提交于 2020-01-11 04:20:06

问题


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

回答1:


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



来源:https://stackoverflow.com/questions/19997399/injecting-session-into-a-model

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