改编自Using knockout js with jquery ui sliders中的答案
<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>
这是自定义绑定:
ko.bindingHandlers.slider = {
init: function (element, valueAccessor, allBindingsAccessor) {
var options = allBindingsAccessor().sliderOptions || {};
$(element).slider(options);
ko.utils.registerEventHandler(element, "slidechange", function (event, ui) {
var value = valueAccessor();
if(!(value < $(element).slider('option', 'min') || value > $(element).slider('option', 'max')))
{
valueAccessor(ui.value);
}
});
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
$(element).slider("destroy");
});
ko.utils.registerEventHandler(element, "slide", function (event, ui) {
var observable = valueAccessor();
observable(ui.value);
});
},
update: function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
if (isNaN(value)) value = 0;
if (value < $(element).slider('option', 'min')) {
value = $(element).slider("option", "min");
} else if (value > $(element).slider('option', 'max')) {
value = $(element).slider("option", "max");
}
$(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());
我也从那个答案改编了jsFiddle 。