我希望能够仅对选择元素应用敲除绑定selectOrDie
以一般地应用selectOrDie。
ko.bindingHandlers.selectOrDie = {
init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
// This will be called when the binding is first applied to an element
// Set up any initial state, event handlers, etc. here
$(element).selectOrDie({
onChange: function() {
console.log(element);
}
});
},
update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
// This will be called once when the binding is first applied to an element,
// and again whenever any observables/computeds that are accessed change
// Update the DOM element based on the supplied values here.
console.log($(element).siblings('span .sod_label').text());
}
};
我不知道如何以selectOrDie注册的更改触发绑定更新的方式进行设置。还是有更好的方法?
这是select元素,没什么特别的:
<select data-bind="selectOrDie: $data" data-custom-class="w60">
<option>10</option>
<option>20</option>
<option>30</option>
<option>50</option>
<option>Alle</option>
</select>
如何制作通常将selectOrDie应用于元素的敲除绑定?
最佳答案
最好的方法是使用敲除提供的现有options绑定,以获取视图模型中某个数组或可观察数组与select
元素之间的双向数据绑定优势。
然后创建一个单独的绑定处理程序,该处理程序允许将selectOrDie小部件应用于相同的select
元素。这是我之前创建的selectOrDie绑定处理程序:
ko.bindingHandlers.selectOrDie = {
init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
// apply selectOrDie widget to select element
$(element).selectOrDie(valueAccessor());
var subsription, options = allBindings()["options"];
// check if bounded collection from "options" binding is observable array
if(options && ko.isObservable(options) && "push" in options){
// ensure changes to bounded collection update selectOrDie widget
subscription = options.subscribe(function(){
$(element).selectOrDie("update");
});
}
// register disposal to clean up after dom node is removed
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
subscription.dispose();
$(element).selectOrDie("destroy");
});
}
};
现在,将此绑定处理程序与现有的
options
绑定结合使用,您可以执行以下操作:
<select data-bind="options: myArray, value: myValue, selectOrDie: { }">
</select>
注意,我已经将一个空对象传递给
selectOrDie
绑定,您还可以传递一个包含有效configuration options的对象,如下所示:
<select data-bind="options: myArray, value: myValue, selectOrDie: {customClass: 'someclass' }">
</select>
检查此工作fiddle。