我对一个看似简单的 Ember 问题感到困惑。我正在使用active_model_serializers meta data serialization从 Rails Controller 序列化我的 Rails current_user 方法,然后使用 this guy's temporary solution 提取 current_user 元 json 并将其设置为全局 ember 变量.
App.CustomRESTSerializer = DS.RESTSerializer.extend({
extractMeta: function(loader, type, json) {
var meta;
meta = json[this.configOption(type, 'meta')];
if (!meta) { return; }
Ember.set('App.metaData', meta);
this._super(loader, type, json);
}
});
到目前为止一切都很好。现在,我可以通过输入 App.metaData.current_user 从控制台访问 current_user 信息,也可以通过调用特定属性从 Handlebars 访问 current_user 信息,即:
{{App.metaData.current_user.email}}
并且该电子邮件属性显示在模板中。当我尝试从 ember Controller 内访问该全局变量时,问题就出现了。这看起来非常简单,但我似乎无法从任何 ember Controller 中访问 current_user 。我尝试过:
currentUserBinding: 'App.metaData.current_user',
currentUser: function() {
return App.metaData.current_user;
}.property(),
Ember.get('App.metaData.current_user')
和其他一些方法,但似乎无法访问它。奇怪的是,我可以通过直接路径从控制台和 Handlebars 内轻松访问 current_user ,但不能从 ember Controller 内访问。我一定错过了一些明显的东西。
非常感谢任何帮助!
最佳答案
在我们的应用程序中,我们按照 @MilkyWayJoe 建议的方式进行操作,但我认为您的方法非常有趣。通过 JSON 传递 current_user 是一种非常优雅的方法。
我没有进行太多实验,但从你的示例中我可以看出,问题与序列化器无关。这是计算属性的问题 - 您需要指定它依赖于 App.metaData.current_user
。
App.ApplicationController = Ember.Controller.extend({
currentUser: function() {
return Ember.get('App.metaData.current_user')
}.property('App.metaData.current_user')
});
这告诉 ember,只要 App.metaData.currentUser
发生变化,它就应该重新计算 currentUser 属性。否则它将运行一次 fx(在 ajax 返回之前)并缓存响应。
关于Ember.js current_user - 从 Controller 访问全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16070390/