我希望能够将我的 Session
单例注入(inject)到我的 Ember 模型中。我试图支持的用例是在模型上计算属性,这些属性对用户的配置文件( session 对象上的属性)使用react。
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');
}
});
注入(inject)在 Controller 中运行良好,但我在将其注入(inject)到模型
时遇到了麻烦。这里有什么限制吗?有什么特殊技巧吗?
--------附加上下文---------
以下是我希望能够在 model
定义中执行的操作的示例:
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')
});
最佳答案
默认情况下,模型中的注入(inject)不起作用。为此,您需要设置标志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');
}
});
这样做的缺点是它会产生一些中断更改:
如果您有
App.Product.FIXTURES = [...]
您需要使用App.Product.reopenClass({ FIXTURES: [...] }) ;
productRecord.constructor === App.Product
将计算为false
。要解决此问题,您可以使用App.Product.detect(productRecord.constructor)
。
关于javascript - 将 session 注入(inject)模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19997399/