Josh Fabian
Josh Fabian

Reputation: 1

Why are controllers singletons in Ember?

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!

Upvotes: 0

Views: 579

Answers (1)

Andrew Hacking
Andrew Hacking

Reputation: 6366

Not all controllers are singletons, most applications when they iterate over a collection will be creating instance controllers for each model. Ember dynamically creates a controller for you.

I use controllers to wrap all my model instances, eg editing a contact with multiple address models

Route based controllers are singletons because routes are singetons and normally persist for the life of the application once instantiated.

Ember doesn't need to tear down controllers and routes when transitioning between routes as the only thing that needs to change on rentering the route is the controllers content/model property.

It is trivial to clear the content of a controller on a route transition if you want to. I just recently answered a question on that which does that and additionally unloads models from the store as well: https://stackoverflow.com/a/26695922/2238268

Singleton controllers can also be useful for managing other state in your application, perhaps gloabal session/authentication state.

So really Ember provides both singleton and instance controllers and they are both used heavily depending on the complexity of your business logic. I tend to keep my models fairly plain and put anything not route related in controllers. I do dirty tracking and undo/reversion in controllers as well as orchestration of persisting model changes in controllers. Aside from the route level controller I have a lot of instance controllers supporting views and implementing the update logic that can span many models.

Upvotes: 1

Related Questions