我想知道如果knockout js会很好地处理以下问题:
我有多个滑块,我想链接到文本框.
当文本框更改时,相应的滑块必须更新为新值,反之亦然.
在更改滑块值或文本框时,需要调用使用所有文本框的输入来计算结果的函数.
使用knockout js以更优雅的方式实现相同的结果是否容易?
我想我将需要创建一个自定义绑定处理程序,就像在jQuery UI datepicker change event not caught by KnockoutJS中完成的那样
解决方法
这是一个例子:
http://jsfiddle.net/jearles/Dt7Ka/
我使用自定义绑定来集成jquery-ui滑块,并使用Knockout来捕获输入并计算净量.
–
UI
<h2>Slider Demo</h2> Savings: <input data-bind="value: savings,valueUpdate: 'afterkeydown'" /> <div style="margin: 10px" data-bind="slider: savings,sliderOptions: {min: 0,max: 100,range: 'min',step: 1}"></div> Spent: <input data-bind="value: spent,valueUpdate: 'afterkeydown'" /> <div style="margin: 10px" data-bind="slider: spent,step: 1}"></div> Net: <span data-bind="text: net"></span>
查看模型
ko.bindingHandlers.slider = { init: function (element,valueAccessor,allBindingsAccessor) { var options = allBindingsAccessor().sliderOptions || {}; $(element).slider(options); ko.utils.registerEventHandler(element,"slidechange",function (event,ui) { var observable = valueAccessor(); observable(ui.value); }); ko.utils.domNodeDisposal.addDisposeCallback(element,function () { $(element).slider("destroy"); }); ko.utils.registerEventHandler(element,"slide",ui) { var observable = valueAccessor(); observable(ui.value); }); },update: function (element,valueAccessor) { var value = ko.utils.unwrapObservable(valueAccessor()); if (isNaN(value)) value = 0; $(element).slider("value",value); } }; var viewmodel = function() { var self = this; self.savings = ko.observable(10); self.spent = ko.observable(5); self.net = ko.computed(function() { return self.savings() - self.spent(); }); } ko.applyBindings(new viewmodel());