Knockout .js with jQuery UI slider

2019-07-18 05:22发布

问题:

Say I have the following jQuery UI sliders that are linked to a textbox.

Is it possible to allow the user to enter values in the textbox that are greater than the sliders value (and set the slider to max)?

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", function (event, 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);
}
};

In this example: http://jsfiddle.net/jearles/Dt7Ka/12/ I would like to be able to save values over 100 in the textboxes and have the sliders appear at their max value.

回答1:

You can do with only updating the observable value in your slidechange event if the observable's value is less then options.max:

ko.utils.registerEventHandler(element, "slidechange", function (event, ui) {
    var observable = valueAccessor();
    var currentMax = $(element).slider("option", "max"); 
    if (observable() <= currentMax)
         observable(ui.value);
});

JSFiddle demo.



回答2:

Put this lines after the line: if (isNaN(value)) value = 0; at the binding update function

if(value>100){
    $(element).slider("option","max",value);          
}

Example:

http://jsfiddle.net/Razaz/Qy6jR/4/

It changes the maximum value of the slider to the new value entered in the textbox if the value is greater than 100

Greetings.