Я построил нечто подобное:
// 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)
И тогда у меня есть класс поля, который используется для указания поля.Хитрость заключается в полях typeXXX
, которые я использую, чтобы определить, что нужно визуализировать.
// 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()
});
Пример:
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});
];
И, наконец, мой шаблонный вид переключает этот массив:
<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>
Шаблоны руля для элементов управления формой:
<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>
<!-- dd/dt deliberately in the wrong order -->
<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>