Reputation: 981
I am working on a web application where I have a select element. I am binding it to a collection. I am doing this using knockout.
Here is my code:
<select multiple class="form-control input-sm"
data-bind="options: ConfigurationParameters ,optionsValue: 'Bit63', optionsText: 'DisplayText', selectedOptions: SelectedConfigParams,select2: { placeholder: 'Choose...' }"></select>
Here is my binding handler:
ko.bindingHandlers.select2 = {
init: function (element, valueAccessor) {
var options = ko.toJS(valueAccessor()) || {};
setTimeout(function () {
$(element).select2(options);
}, 0);
},
update: function (element, valueAccessor, allBindings) {
console.log("update called");
}
};
I have other select elements all with similar functionality. When a user selects required information and click submit, I am saving the data to a data base. After doing this I need to clear the values in the select boxes. I wrote a code to remove all the elements from 'SelectedConfigParams'. But the values are not getting removed from the select element. In the image, you can see, after clearing the selected options , the select element is still showing the previous selected values. (SelectedConfigParams is an ko.observableArray()).
Upvotes: 2
Views: 1648
Reputation: 39055
Whe you create a custom binding you need to specify two different functions:
valueAccessor
, which allows you to get the value or observable specified after the bindingName:
, or through any of the other parameters (allBindings, viewModel, bindingContext
). You should update the state of the element, the applied plugins and so on in this function, depending on the new observable valuesSo, what you need to do is:
init
function to initialize the select2
update
function to change the state of the select2
pluginupdate
function of your binder will be called, so that the state of your element or plugin can be updatedPlease see Knockout's custom binding docs for more info.
Upvotes: 4