Here's a slight improvement over other implementations of bootstrap select in knockout.
What this does is subscribe to observables in value, selectedOptions, options, and disable bindings.
So if you use the "disable" binding on the same element where you user "bootstrapSelect" below, then it will add the disabled class or remove it based on the value of the observable you bind to the disable binding.
ko.bindingHandlers.bootstrapSelect = new function () {
this.after = ['options', 'value', 'selectedOptions'];
this.init = function (element, valueAccessor, allBindings, viewModel, bindingContext) {
var $e = $(element);
var subscriptions = [];
var doRefresh = function () {
$e.selectpicker('refresh');
};
var addSubscription = function (bindingKey, callBack) {
var targetObs = allBindings.get(bindingKey);
if (targetObs && ko.isObservable(targetObs)) {
subscriptions.push(targetObs.subscribe(callBack));
}
};
addSubscription('disable', () => {
$e.addClass('disabled');
doRefresh();
});
addSubscription('options', doRefresh);
addSubscription('value', doRefresh); // Single
addSubscription('selectedOptions', doRefresh); // Multiple
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
while (subscriptions.length) {
subscriptions.pop().dispose();
}
});
};
this.update = function (element, valueAccessor, allBindings, viewModel, bindingContext) {
var $e = $(element);
};
};
export default ko.bindingHandlers.bootstrapSelect;
Heres an example:
<select class="form-control" data-live-search="true" data-bind="disable: readOnly, bootstrapSelect: { }, options: selectOptions, optionsText: 'name', optionsValue: 'value', value: userValue"></select>
<span class="validationMessage" style="" data-bind="visible: !userValue.isValid() && (userValue.isModified() || userValue.isValidating()), text: userValue.error()"></span>
In this example i have an observable called readOnly bound to the disable binding and I can toggle it between true and false. If I set true for readOnly then the disable binding adds a "disabled" attribute to the element, which bootstrap select ignores. But the subscription to "readOnly" in the bootstrap select binding will be fired and cause it to check the value of the disable binding and then add or remove the class "disabled" which bootstrap select respects.
The subscription to options, value, and selectedOptions also ensures the refresh is called on Bootstrap select to update the gui with new options or selected values.