Multiple Controller Instances



I’m currently evaluating Ember for a new app I’m building. I’m trying to understand how to do things the “Ember way” and use the framework the way it was designed. I have a question around multiple controller instances.

The app involves a lot of dynamic form generation. When selecting a form, the server returns a JSON structure that describes what controls to render. I’ve managed to make some progress by using a custom helper to render the required form element:

<div class="panel-body">
 <form class="form-horizontal">
  {{#each control in controls}}
   {{renderControlView control}}
  <div class="form-group">
   <div class="col-md-offset-2 col-md-10">
    <button {{action 'generate'}} type="button">Generate</button>

The custom helper then uses the “render” helper to create an instance of a view, with it’s controller:

Ember.Handlebars.registerBoundHelper( 'renderControlView', function ( filter ) {
	return Ember.Handlebars.helpers.render.apply( this, args );

This works.

However, lets say I have a view/controller combination for a date selection control. If I have a multiple instances of a date control on a single form, they will all share the same controller instance? Is that correct? If so, that would prevent me from including any instance-specific state on the controller, such as validation state.

What would be the best way to handle this using Ember?



Bump - any suggestions at all?



Using the render helper will result in a singleton instance of your controller. However, there are ways to avoid this. If you really want to stick with a view and controller, you can manually register your controller as a non-singleton.

var DateFormController = Ember.Controller.extend({});
App.register('controller:date-form', DateFormController, { singleton: false });

However, for your use case, I highly recommend using a component instead. Form controls are really the ideal use case for components, as components aren’t singletons and they combine both view and controller logic. And this question even shows you how to render a component dynamically.