I am using a Knockout model, and I wish to update values in this model using a jQuery UI range slider. Consider the following example:
Model:
var ViewModel = function () {
var self = this;
self.MinTerm = ko.observable();
self.MaxTerm = ko.observable();
}
ko.applyBindings(new ViewModel());
Now, a jQuery UI range slider should update these two values. This (very ugly) solution came close, the values in my ViewModel are being updated, but somehow this is not reflected in controls bound to these values, such as:
HTML
<div id="sliderTerms"></div>
<span data-bind="text: MinTerm"></span>
<span data-bind="text: MaxTerm"></span>
Script:
$("#sliderTerms").slider({
range: true,
min: 6,
max: 120,
values: [6, 120],
step: 1,
slide: function (event, ui) {
ViewModel.MinTerm = ui.values[0];
ViewModel.MaxTerm = ui.values[1];
}
});
Now, it would be really nice if I could bind to a custom bindingHandler such as this, which works great for binding a slider to a singular value in my KO model:
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);
}
};
This is where I get stuck. Is it possible to assign an array of valueAccessors, for example, so I can perform something like this:
<div id="sliderTerms" data-bind="rangeSlider: [MinTerm, MaxTerm], sliderOptions: {min: 6, max: 120, range: true, step: 1}"></div>
Thanks!