我需要使用一个全局变量(用户上下文,可从所有代码获得)我已经阅读了一些关于这个主题的帖子,但我没有一个明确的答案.
App = Ember.Application.create({
LOG_TRANSITIONS: true,
currentUser: null
});
Run Code Online (Sandbox Code Playgroud)
Mik*_*tti 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({});
Run Code Online (Sandbox Code Playgroud)
如何从应用程序中使用的所有控制器更新和访问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'));
}
)}
Run Code Online (Sandbox Code Playgroud)
如果您需要从视图/模板访问currentUser,只需使用needs它通过本地控制器访问它.如果您需要路由,请使用路由的controllerFor方法.