0
votes

I'm trying to understand controllers in the new router system. I understand they exist to decorate models and present non-permanent state to the view/template for rendering. And I understand the conventions the Ember router uses to instantiate and set up single copies of each controller from route names. But does that mean you should never have more than one copy of a controller?

Here's my use case: I have a set of nested lists of items with complex non-persistent per-item state (different levels of collapsed / visible nesting, different editing modes, etc). I don't think this belongs in the view, and it's too complicated (because of nesting) to keep in a singleton controller -- so I was planning to have one controller instance per one view instance (all the same controller and view class though). Is this sound?

Second, simpler question. How do I access the controllers that Ember router instantiates? Previously, you could do App.get('router.postController') but that no longer works.

1

1 Answers

1
votes

First Question

Not all controllers are singletons. There are cases where Ember.js creates non-singleton controllers for you.

One case is when using itemController with {{each}} helper:

{{#each model itemController="post"}}
  <!-- template here -->
{{/each}}

This will create a new instance of App.PostController for every post item in the loop.

One other case is when you use the {{render}} helper and pass a model to it:

{{render "post" firstPost}}
{{render "post" secondPost}}

This will create a separate App.PostController instance for every {{render}}.

Second Question

It depends where you want to access them from.

From the route:

this.controllerFor("post");

From another controller:

App.CommentController = Ember.ObjectController.extend({
  needs: ['post'],
  test: function() {
    return this.get('controllers.post');  // this returns the post controller
  }
});

More info on that here: http://emberjs.com/guides/controllers/dependencies-between-controllers/

From the view:

this.get('controller');