從答案適應於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了。
的問題是,[此功能](https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.slider.js#L505 )被調用,這將強制您將滑塊分配到最小和最大範圍內的值。簡短的回答是「不,不可能在其範圍之外的滑塊上設置一個值」,除非您願意覆蓋我鏈接的功能。 – 2013-03-07 12:56:43
重寫該功能有多容易?我認爲擴展jquery-ui庫可能是實現這一目標的唯一途徑。 – woggles 2013-03-07 13:05:04
可能不會太糟糕。我會看看我能不能拿出一些東西:) – 2013-03-07 13:05:46