Last active
May 3, 2017 01:34
-
-
Save tohagan/9d9055f43a5857341dc350b5e1bd3cf1 to your computer and use it in GitHub Desktop.
Knockout binding for bootstrap-slider. Fixes case when jQuery UI is already bound to $(element).slider().
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Slider: https://github.com/seiyria/bootstrap-slider | |
// When $(element).slider() is already defined by jQuery UI | |
// we use the alternative binding $(element).bootstrapSlider() | |
ko.bindingHandlers.sliderValue = { | |
init: function (element, valueAccessor, allBindings, viewModel, bindingContext) { | |
var params = valueAccessor(); | |
var slider = $.fn.slider ? 'bootstrapSlider' : 'slider'; | |
// Check whether the value observable is either placed directly or in the paramaters object. | |
if (!(ko.isObservable(params) || params['value'])) | |
throw "You need to define an observable value for the sliderValue. Either pass the observable directly or as the 'value' field in the parameters."; | |
// Identify the value and initialize the slider | |
var valueObservable; | |
if (ko.isObservable(params)) { | |
valueObservable = params; | |
$(element)[slider]({ value: ko.unwrap(params) }); | |
} | |
else { | |
valueObservable = params['value']; | |
// Replace the 'value' field in the options object with the actual value | |
params['value'] = ko.unwrap(valueObservable); | |
$(element)[slider](params); | |
} | |
// Make sure we update the observable when changing the slider value | |
$(element).on('slide', function (ev) { | |
valueObservable(ev.value); | |
}); | |
}, | |
update: function (element, valueAccessor, allBindings, viewModel, bindingContext) { | |
var slider = $.fn.slider ? 'bootstrapSlider' : 'slider'; | |
var modelValue = valueAccessor(); | |
var valueObservable; | |
if (ko.isObservable(modelValue)) | |
valueObservable = modelValue; | |
else | |
valueObservable = modelValue['value']; | |
$(element)[slider]('setValue', valueObservable()); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment