将会话注入模型 [英] Injecting session into a model

查看:115
本文介绍了将会话注入模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将我的 Session 单例注入我的Ember模型。我试图支持的用例是在模型上计算属性,该属性对用户的配置文件(Session对象上的一个属性)做出反应。

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

注入在控制器中正常工作,但是遇到麻烦, $ C>模型。这里有什么限制吗?任何特殊技术?

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


推荐答案

默认情况下,模型中的注入不起作用。为此,您需要设置标志 Ember.MODEL_FACTORY_INJECTIONS = true

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:


  • 如果您有 App.Product.FIXTURES = [...] 您需要使用 App.Product.reopenClass({FIXTURES:[...]});

productRecord.constructor === App.Product 将评估为 false 。要解决这个问题,您可以使用 App.Product.detect(productRecord.constructor)

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

这篇关于将会话注入模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆