Reputation: 31
I am trying to get 2 widgets to appear in multiple routes in an ember.js application. I have set up the following as a demo, http://jsfiddle.net/adice/EyDcy/5/
You will see that I have found a way to do this by adding the following to a route:
App.IndexRoute = Em.Route.extend({
setupController: function(controller,model) {
this._super(controller,model);
controller.set('user',App.UsersStore.find(2));
controller.set('site',App.SiteData.find(1));
}
});
But if i want to have this available to every route, do i really have to manually add it to all routes that i make? I tried to add it to the ApplicationRoute, but that kept returning an error.
Also is the a way to populate the id? I'd like to do
App.appData = Em.Object.create({
currentUserId: 2
});
App.IndexRoute = Em.Route.extend({
setupController: function(controller,model) {
this._super(controller,model);
controller.set('user',App.UsersStore.find(App.appData.currentUserId));
controller.set('site',App.SiteData.find(1));
}
});
Upvotes: 2
Views: 814
Reputation: 64
Since you want to access that user object in every route you don't have to rely on your router, but probably can think of the user object as a global variable which you want to access from everywhere in your app. There are several places where to store these objects. In this updated version of your jsfiddle i have put it in the ApplicationController's "currentUser" property:
App.ApplicationController = Ember.Controller.extend({
init: function() {
this.set('currentUser', App.UsersStore.find(2))
}
});
Using the "needs" syntax you can access other controllers from other controllers. See the UserDetailsController:
App.UserDetailsController = Ember.ObjectController.extend({
needs: 'application',
content: Ember.computed.alias('controllers.application.currentUser')
})
One thing which i just understood how to use is the {{render}} helper:
{{render "user_details"}}
With this you can render arbitrary templates ("user_details") + controllers ("UserDetailsController") anywhere in your app, no matter which Route you are at. (I think this is what ember.js people mean when they are talking about "singleton controllers".)
Combine all this and i hope you have a better idea about how to approach your problem.
Upvotes: 2