我创建了一个自定义绑定处理程序来呈现一个 html 选择组件。
例如:
<select data-bind="dynamicSelect: { src: 'Category', label: 'Category'} "></select>
用户选择一个类别后,类别字段数组被填充,我已将其绑定到将呈现某个模板的 div
<div data-bind="template: { name: displayMode, foreach: categoryFields }"></div>
我的模板
<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>
问题是,模板内的 dynamicSelect 似乎没有绑定?我将如何在模板中重用绑定处理程序?
绑定处理程序
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) {
}
});
});