selectpicker not working with Knockout.js
Hi
I have an app that uses bootstrap-select (selectpicker) for dropdown options. I am using knockout.js to integrate with the server, where a normal
The following using bootstrap-select fails:
this comes up as "nothing selected"
Does bootstrap-select support Knockout?
PS the selectpicker works fine as expected without "data-bind" and the knockout code also works fine in the same file.
Any ideas?
+1 here - I also would like to integrate this into a KO app...
I got it working on chrome and FF with the new DOM4 mutations API so that I can call bootstrap-select's refresh.. Obviously wont work on IE... it would be good to have a solution that works everywhere
code:
(function () {
MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
if (!MutationObserver) return;
console.log ("running select picker init");
$('.selectpicker').selectpicker();
var observer = new MutationObserver(function (mutation, observer) {
console.log("In mutation observer:",mutation,observer);
$('.selectpicker').selectpicker('refresh');
});
observer.observe($(".selectpicker")[0],
{
subtree:true,
attributes:true,
attributeFilter: ['value', 'disabled']
});
})();
I use a custom handler for ko:
ko.bindingHandlers.dropdown = {
init: function (element, valueAccessor, allBindingsAccessor) {
var options = allBindingsAccessor().dropdownOptions|| {};
$(element).selectpicker(options);
ko.utils.registerEventHandler(element, "change", function () {
$(element).selectpicker('refresh');
});
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
// TODO: destroy method for selectpicker
//$(element).selectpicker("destroy");
});
},
update: function (element, valueAccessor) {
$(element).selectpicker('refresh');
}
};
Markup example:
<select data-bind="dropdown: value, dropdownOptions: { data-width: '100%', 'data-size': 5 }">
</select>
@gomoimihai - good one...
Unfortunately, I couldn't use it in my scenario - the dropdown option states change based on which page the user is on currently - so in that case, the update isn't fired at all since the observable hasnt changed -so I ended up having to look into dom mutation events.
Guys - Many thanks here and apologies for the late reply, I have been travelling so only now starting to pick this up again!
Yes please integrate it with Knockout
+1 from me
I created a custom binding as shown below:
ko.bindingHandlers.selectPicker = {
init: function (element, valueAccessor, allBindingsAccessor) {
if ($(element).is('select')) {
if (ko.isObservable(valueAccessor())) {
ko.bindingHandlers.value.init(element, valueAccessor, allBindingsAccessor);
}
$(element).selectpicker();
}
},
update: function (element, valueAccessor, allBindingsAccessor) {
if ($(element).is('select')) {
var selectPickerOptions = allBindingsAccessor().selectPickerOptions;
if (typeof selectPickerOptions !== 'undefined' && selectPickerOptions !== null) {
var options = selectPickerOptions.options,
optionsText = selectPickerOptions.optionsText,
optionsValue = selectPickerOptions.optionsValue,
optionsCaption = selectPickerOptions.optionsCaption;
if (ko.utils.unwrapObservable(options).length > 0) {
ko.bindingHandlers.options.update(element, options, ko.observable({ optionsText: optionsText, optionsValue: optionsValue, optionsCaption: optionsCaption }));
}
}
if (ko.isObservable(valueAccessor())) {
ko.bindingHandlers.value.update(element, valueAccessor);
}
$(element).selectpicker('refresh');
}
}
};
You can call this in 3 ways. If you just want to add the basic selectpicker functionality to a dropdown in your view:
<select data-bind="selectPicker: true">
<option>Option 1</option>
<option>Option 2</option>
</select>
If you want to bind the selected value to an observable:
<select data-bind="selectPicker: myObservable">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
Or if you're binding to an observable, and the options in your dropdown are also being generated by another observableArray in your viewmodel:
<select data-bind="selectPicker: myObservable, selectPickerOptions: { options: myObservableArray, optionsText: 'myTextField', optionsValue: 'myValueField', optionsCaption: 'Please select...' }"></select>
The latter basically implements the built-in Knockout options binding.
Hope this helps.
+1 I had to disable bootstrap-select in my app because knockout did not work with it. I'd love to get it enabled again.
Agreed. Going to have to turn off bootstrap-select until there's proper integration with Knockout.
Guys - I've taken it out already. Hopefully there will be an update to bootstrap-select as the base Bootstrap select is not very nice. BR Sean
I'll take a look and see if I can finally get to the bottom of this.
I can suggest to call selectpicker() after dropdown initialization - worked for me. I call the method after receiving items via ajax and pushing them into observable array.
Thanks MattWorrall! The custom binding you provided works great. The only issue that I'm having is that 'myObservable' is being set to the option value and not the object within the array. Is there a way of setting the observable to the object?
I've updated the binding since I last posted - this is the version I now use and it seems to work well in all the scenarios I use it:
/*
* Custom Knockout binding to apply the selectpicker widget (bootstrap-select) to a bound dropdown and
* refresh it when the contents of the dropdown change.
*
* The binding can be used in two ways:
*
* 1. If you don't want to bind the dropdown's selected option to an observable, just use data-bind="selectPicker: true"
* 2. If you wish to bind the dropdown's selected option to an observable, so that when a different option is selected
* in the list it updates the observable, use data-bind="selectPicker: myObservable".
* If the options in the dropdown are generated from an observableArray, you can wrap the standard Knockout options binding parameters
* in a selectPickerOptions object
*
* ie. data-bind="selectPicker: myObservable, selectPickerOptions: { options: myOptionsObservableArray, optionsText: 'arrayTextField', optionsValue: 'arrayValueField', optionsCaption: 'Please select...', disabledCondition: someBooleanExpression, resetOnDisabled: true|false }"
*
* Note the two further parameters in the selectPickerOptions object, disabledCondition and resetOnDisabled. If provided, disabledCondition should be a boolean expression, that when evaluated as true will cause the selectpicker to be disabled.
* The resetOnDisabled parameter, if true, will cause the selected index of the dropdown to be reset to zero when it is disabled.
*
* Note requires that bootstrap-select.js is included in the view
*/
ko.bindingHandlers.selectPicker = {
init: function (element, valueAccessor, allBindingsAccessor) {
if ($(element).is('select')) {
if (ko.isObservable(valueAccessor())) {
if ($(element).prop('multiple') && $.isArray(ko.utils.unwrapObservable(valueAccessor()))) {
// in the case of a multiple select where the valueAccessor() is an observableArray, call the default Knockout selectedOptions binding
ko.bindingHandlers.selectedOptions.init(element, valueAccessor, allBindingsAccessor);
}
else {
// regular select and observable so call the default value binding
ko.bindingHandlers.value.init(element, valueAccessor, allBindingsAccessor);
}
}
$(element).addClass('selectpicker').selectpicker();
}
},
update: function (element, valueAccessor, allBindingsAccessor) {
if ($(element).is('select')) {
var selectPickerOptions = allBindingsAccessor().selectPickerOptions;
if (typeof selectPickerOptions !== 'undefined' && selectPickerOptions !== null) {
var options = selectPickerOptions.options,
optionsText = selectPickerOptions.optionsText,
optionsValue = selectPickerOptions.optionsValue,
optionsCaption = selectPickerOptions.optionsCaption,
isDisabled = selectPickerOptions.disabledCondition || false,
resetOnDisabled = selectPickerOptions.resetOnDisabled || false;
if (ko.utils.unwrapObservable(options).length > 0) {
// call the default Knockout options binding
ko.bindingHandlers.options.update(element, options, ko.observable({ optionsText: optionsText, optionsValue: optionsValue, optionsCaption: optionsCaption }));
}
if (isDisabled && resetOnDisabled) {
// the dropdown is disabled and we need to reset it to its first option
$(element).selectpicker('val', $(element).children('option:first').val());
}
$(element).prop('disabled', isDisabled);
}
if (ko.isObservable(valueAccessor())) {
if ($(element).prop('multiple') && $.isArray(ko.utils.unwrapObservable(valueAccessor()))) {
// in the case of a multiple select where the valueAccessor() is an observableArray, call the default Knockout selectedOptions binding
ko.bindingHandlers.selectedOptions.update(element, valueAccessor);
}
else {
// call the default Knockout value binding
ko.bindingHandlers.value.update(element, valueAccessor);
}
}
$(element).selectpicker('refresh');
}
}
};
Hope this helps!
Thanks MattWorall the above updated custom binding of yours is working super fine. Made my work :+1:
No problem, glad it helps
I wasn't able to get the object returned, but I created a computed observable that returns the object based on the selected id. Thanks again MattWorall, this helped out a great deal.
Doesn't work for me... there something wrong with the binding
Object function c(){if(0<arguments.length)return c.equalityComparer&&c.equalityComparer(d,arguments[0])||(c.O(),d=arguments[0],c.N()),this;a.i.lb(c);return d} has no method 'get';
This is my html
<select data-bind="selectPicker: filter, selectPickerOptions: { options: filters, optionsText: 'title', optionsValue: 'title', optionsCaption: 'Please select...' }"></select>
Does anyone have a working Gist?
@vincenttheeten , seems the issue is that the allBindingsAccessor behaves differently in knockout 3.0.0, which you're probably using. I can't get it to work as well.