Is it a good practice to set the currentUser global variable in the App object ?
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({});
How to update and access the currentUser property from all the controllers used in the app ?
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'));
}
)}
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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…