Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to put global state in Ember.js?

Tags:

ember.js

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?

like image 981
stephanos Avatar asked Feb 17 '23 14:02

stephanos


1 Answers

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

like image 126
Mike Grassotti Avatar answered Mar 17 '23 02:03

Mike Grassotti