我需要使用全局变量(用户上下文,可从所有代码获得) 我已经阅读了一些关于这个主题的帖子,但我没有明确的答案。
App = Ember.Application.create({
LOG_TRANSITIONS: true,
currentUser: null
});
答案 0 :(得分:58)
在App对象中设置currentUser全局变量是一个好习惯吗?
不,这不是一个好习惯。您应该避免使用全局变量。该框架为实现这一目标做了很多工作 - 如果您发现自己认为全局变量是最佳解决方案,则表明某些事情应该被重构。在大多数情况下,正确的位置在控制器中。例如,currentUser可能是:
//a property of application controller
App.ApplicationController = Ember.Controller.extend({
currentUser: null
});
//or it's own controller
App.CurrentUserController = Ember.ObjectController.extend({});
如何从应用程序中使用的所有控制器更新和访问currentUser属性?
使用needs
属性。假设您已将currentUser声明为ApplicationController的属性。它可以从PostsController访问,如下所示:
App.PostsController = Ember.ArrayController.extend{(
needs: ['application'],
currentUser: Ember.computed.alias('controllers.application.currentUser'),
addPost: function() {
console.log('Adding a post for ', this.get('currentUser.name'));
}
)}
如果您需要从视图/模板访问currentUser,只需使用needs
使其可通过本地控制器访问。如果您需要路线,请使用路线的controllerFor方法。