如何在Knockout绑定输入中使用
jQuery UI Spinner小部件?
<tbody data-bind="foreach: orders"> <tr> <td data-bind="text: Name"></td> <td><input type="number" style="width: 100px;" data-bind="value: Price" /></td> <td><input type="number" style="width: 50px;" data-bind="value: VAT" /></td> <td><input type="number" style="width: 50px;" data-bind="value: Number" /></td> <td data-bind="text: Final()"></td> <td><a href="javascript:void(0);" data-bind="click: $root.removeOrder">Remove</a></td> </tr> </tbody>
解决方法
最好的方法是创建自定义绑定以将微调框绑定到输入:
ko.bindingHandlers.spinner = { init: function(element,valueAccessor,allBindingsAccessor) { //initialize spinner with some optional options var options = allBindingsAccessor().spinnerOptions || {}; $(element).spinner(options); //handle the field changing ko.utils.registerEventHandler(element,"spinchange",function () { var observable = valueAccessor(); observable($(element).spinner("value")); }); //handle disposal (if KO removes by the template binding) ko.utils.domNodeDisposal.addDisposeCallback(element,function() { $(element).spinner("destroy"); }); },update: function(element,valueAccessor) { var value = ko.utils.unwrapObservable(valueAccessor()),current = $(element).spinner("value"); if (value !== current) { $(element).spinner("value",value); } } };
然后只是使用它而不是值绑定:
<input type="number" style="width: 100px;" data-bind="spinner: Price,spinnerOptions: { min: 0 } " />