Ember.js 从任何应用程序控制器访问全局变量
我需要使用一个全局变量(用户上下文,可从所有代码中获得) 我读过一些关于这个话题的帖子,但我没有一个明确的答案Ember.js 从任何应用程序控制器访问全局变量,ember.js,Ember.js,我需要使用一个全局变量(用户上下文,可从所有代码中获得) 我读过一些关于这个话题的帖子,但我没有一个明确的答案 App = Ember.Application.create({ LOG_TRANSITIONS: true, currentUser: null }); 在App对象中设置currentUser全局变量是一种好的做法吗 如何从应用程序中使用的所有控制器更新和访问currentUser属性 在App对象中设置currentUser全局变量是一种好的做法吗 不,这不是一个好的做
App = Ember.Application.create({
LOG_TRANSITIONS: true,
currentUser: null
});
//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方法。我有几个应用程序级布尔属性,这些属性将在几乎所有视图/模板中使用。如果我在applicationController
中定义它们,那么我必须在所有控制器中定义needs
属性。如果我在App中定义它们,那么就不需要需要
。有什么想法吗?我可以看到一个在应用程序级别设置一些布尔属性的参数,比如ember本身定义了LOG_转换。任何更复杂的东西都应该放在def自己的控制器中。如果您希望一个控制器在所有其他控制器中都可用,则可以使用初始值设定项将其注入其他控制器中。有关使CurrentUserController
作为所有控制器的currentUser
属性可用的示例,请参阅。可以很容易地对ConfigController执行相同的操作。Ember.Computed应该是Ember.Computed,运行此命令时出现错误。。。显然,第二个冒号currentUser:@jsetting32这篇文章应该更新为:currentUser:Ember.computed.alias('controllers.Application.currentUser'),