I built something like this:
// superclass for all form field views App.FormFieldView = Ember.View.extend({ classNames: 'formFieldView', field: null, ... }); // form field with just text App.FormFieldTextView = App.FormFieldView.extend({ templateName: 'formfield-text', ... }); // form field with checkbox App.FormFieldCheckboxView = App.FormFieldView.extend({ templateName: 'formfield-checkbox', ... }); ... and so on (have more types for date selector, select lists etc)
And then I have a field class that is used to specify a field. The trick is the typeXXX fields that I use to determine what to do.
// field definition in controller. App.Field = Ember.Object.extend({ label: null, required: true, value: null, typeText: function () { // defaults to typeText return !(this.get('typeDate') || this.get('typeSelect') || this.get('typeCheckbox') || this.get('typeInfo')); }.property('typeDate', 'typeSelect', 'typeCheckbox', 'typeInfo').cacheable() });
Example:
var fields = [ App.Field.create({ label: 'First name', valueBinding: 'App.model.firstName' }), App.Field.create({ label: 'I have a valid work permit for working in India.', valueBinding: 'App.model.validWorkingIndia', typeCheckbox: true}); ];
And finally, my template view makes a switch in this array:
<fieldset> <dl> {{#each fields}} {{#if typeText}} {{view App.FormFieldTextView fieldBinding="this"}} {{/if}} {{#if typeCheckbox}} {{view App.FormFieldCheckboxView fieldBinding="this"}} {{/if}} ... more types here {{/each}} </dl> </fieldset>
Handle templates for form controls:
<script type="text/x-handlebars" data-template-name="formfield-text"> <dt><label> {{field.label}}{{#if field.required}}*{{/if}} </label></dt> <dd>{{view Ember.TextField valueBinding="field.value"}}</dd> </script> <script type="text/x-handlebars" data-template-name="formfield-checkbox"> <dd class="checkbox"> {{view Ember.Checkbox valueBinding="field.value"}} </dd> <dt class="checkbox"><label>{{field.label}}{{#if field.required}}*{{/if}} </label></dt> </script>