Why are controllers singletons in Ember?

Hey guys, I’m hoping someone can clear this up for our team. Why exactly are controllers singletons which don’t get reset on navigation? In what situations is it better for them to not reset every time. I’ve heard “Controllers as singletons make perfect sense in any long-lived application” but non ember devs I’ve talked to were equally confused by this. Is this a design flaw that is being improved in the future or are we just looking at things the wrong way?

Hoping for a really clear answer I can take back to the team. Thanks everyone! :slight_smile:

I can’t speak for what the design intention was, but I don’t believe it was accidental and I might be able to give you some examples of why I think it was a smart decision.

  • Until a controller is loaded with new data, what good reason is there to reset its state? Controllers are all visible to each other (via the “needs”) property, and it’s valid and common to examine the state of controllers that may not be a part of the active route.
  • If you have a route that looks like collection/group/item, shouldn’t the state of collection and group stay consistent even as you navigate to new items? Doesn’t that imply that the natural state of the controller is to stay constant until changed?
  • It’s not hard to blow out the singleton instance and get a fresh one. The setupController hook in the route will give you a new controller, as will transitioning to a route and passing an explicit model, and you can tie stuff that absolutely should be refreshed on each model change to .observes(“model”).

In general, I found a lot of these kinds of architectural things very frustrating when I first started working with Ember. When you start “thinking Ember,” you become very grateful for them. Almost everything I was frustrated I couldn’t do for the first 4 months, I was grateful for during the next 4.

4 Likes

In Ember 2.0, routable components (which are going to replace controllers) will not be singletons. You’ll still be able to use singletons via services (I believe).

The reasons @kylecoberly states are valid, but the consensus seems to be that the surprises that come with singleton controllers aren’t worth the benefits.

1 Like