从任何应用程序控制器访问全局变量

问题描述:

我需要使用全局变量(用户上下文,可从所有代码中获取)
我已经阅读了有关此主题的一些帖子,但我没有一个明确的答案。

I need to use a global variable (user context, available from all the code) I have read some posts regarding this topic but I do not have a clear answer.

App = Ember.Application.create({
  LOG_TRANSITIONS: true,
  currentUser: null
});




  1. 在应用程序中设置currentUser全局变量是一个好习惯对象?

  2. 如何从应用程序中使用的所有控制器更新和访问currentUser属性?



在App对象中设置currentUser全局变量是个好习惯吗?

Is it a good practice to set the currentUser global variable in the App object ?

不,这不是一个好习惯。你应该避免使用全局变量。框架做了很多工作,以使这成为可能 - 如果你发现自己认为一个全局变量是最好的解决方案,这是一个应该被重构的标志。在大多数情况下,正确的地方在控制器中。例如,currentUser可以是:

No, this is not a good practice. You should avoid using global variables. The framework does a lot to make this possible - if you find yourself thinking a global variable is the best solution it's a sign that something should be refactored. In most cases the right place is in a controller. For example, currentUser could be:

//a property of application controller
App.ApplicationController = Ember.Controller.extend({
  currentUser: null
});

//or it's own controller
App.CurrentUserController = Ember.ObjectController.extend({});




如何从所有使用的控制器更新和访问currentUser属性应用程序?

How to update and access the currentUser property from all the controllers used in the app ?

使用需要属性。假设你已经将currentUser声明为ApplicationController的属性。它可以从PostsController这样访问:

Use the needs property. Let's say you've declared currentUser as a property of ApplicationController. It can be accessed from PostsController like this:

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,只需使用需要使其可通过本地控制器访问。如果您需要路由,请使用路由的controllerFor方法。

If you need to access currentUser from a view/template, just use needs to make it accessible via the local controller. And if you need it from a route, use the route's controllerFor method.