I created a special binding handler to render the html select component.
EG:
<select data-bind="dynamicSelect: { src: 'Category', label: 'Category'} "></select>
After the user selects a category, the array of category fields is filled, and I attached to a div that will display a specific template
<div data-bind="template: { name: displayMode, foreach: categoryFields }"></div>
My templates
<script type="text/html" id="inputTemplate"> <label data-bind="text: FieldName, attr: { for: FieldName }"></label> <input data-bind="attr: { name: FieldName, type: $parent.fieldType($data) }" /> </script> <script type="text/html" id="lookupTemplate"> <label data-bind="text: FieldName, attr: { for: FieldName }"></label> <select data-bind="dynamicSelect: { src: FieldName, label: FieldName}"></select> </script>
Is the problem that dynamicSelect inside the template is optional? How can I reuse the binding handler inside the template?
Binding handler
define(['durandal/composition', 'plugins/http'], function (composition, http) { composition.addBindingHandler('dynamicSelect', { init: function (element, valueAccessor) { console.log(element); console.log(valueAccessor()); var elem = $(element); elem.addClass('hidden'); elem.before('<label>' + valueAccessor().label + '</label>'); elem.after('<div><br/><label><i class="icon-spinner icon-spin active"></i> Loading...</label></div>'); console.log('/api/lookup?type=' + valueAccessor().src); return http.get('/api/lookup?type=' + valueAccessor().src).then(function (res) { var items = res.LookupItems; $.each(items, function (idx) { elem.append('<option value=' + items[idx].Id + '>' + items[idx].Name + '</option>'); }); elem.removeClass('hidden'); elem.next().addClass('hidden'); }); }, update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { } }); });
source share