In my Ember.js application users can have multiple projects. Since only one project can be viewed at a time, the active project is selected via the navigation bar. This is basically a global state (which is also reflected in the URL /projects/xyz
).
Since multiple components depend on the project selection, where do I put this information? And in what form do I save it (instance or id)?
About my status quo: I have a route that intercepts the call to setupController
for /projects/:project_id
and uses App.set("projectId", model)
to place the instance in the global namespace. This seems bad, doesn't it?
Whenever you have global state that is reflected in the url you can use the ember router to manage that state.
For example, let's say you have a tasks resource nested under project like:
App.Router.map(function() {
this.resource('project', { path: '/projects/:project_id' }, function() {
this.route('edit');
this.resource('tasks', function() {
this.route('new');
});
});
});
Ember will use the project_id url segment to find your model and set it as the content of ProjectController. To access the currently selected project from another controller, declare a dependency using the needs
array and access it via the controllers
property.
App.TasksController = Ember.ArrayController.extend({
needs: ['project']
});
// tasks/index.hbs
Project name: {{controllers.project.name}}
See controllers-needs-explained
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With