11
votes

I've been using Ember for a while but still struggling sometimes to find out the best practices. So one of the Ember ways regarding controller and view is

an opinion of Ember's designers, that is enforced by the router is that for a given BaseName (e.g. "Application," "CustomerEntry," "My Items") there should be a BaseNameView and a BaseNameController. -- Ember guide

The problem is that what if I want multiple instances of the same view on a page. Since the controller is created during initiation of the application, they are singletons under the application namespace, which will not be able to hold two instances of the model data.

One solution I see is to create controllers(and model data) manually and pass them to views. But in this case, I'd like Ember not create controllers automatically for me. Put it another way, why would Ember creates controllers as singletons during application startup.

1
Are you sure that you need to have multiple instances of the same controller? It sounds like you could have different controllers associated with the distinct views that you require. The controllers don't hold different instances of model data, they generally proxy the data to the view using bindings. My understanding of Ember architecture is that the idea with Views is that are responsible strictly for DOM/CSS stuff and handling user events. Application logic remains at the router/controller level so maybe it makes sense to have multiple distinct controllers, even if they proxy the same data.Sean O'Hara

1 Answers

2
votes

I think there are many use cases where a View type doesn't have a corresponding Controller type. Especially when the type of view is more like a UI widget than a full-fledged application feature. Many views can share the same controller. Take a look at this applicationView template:

<h1>Here are two files, compare them</h1>
{{view App.MyFileView contentBinding="leftFileContent"}}
{{view App.MyFileView contentBinding="rightFileContent"}}

This creates two instances of my view class and binds their content properties to two different properties on the applicationController. The controller property for both of those views is set to the singleton applicationController instance.

One possible reason why controllers are singletons could be that they're able to be addressed in the global namespace via something like App.router.myController.