B"H
I am working on an old project based on knockout js.
I am trying to create a custom binding (for select2), but I am running into a brick wall trying to figure out which attributes (values) are the ones that changed.
i.e how do I know whether the list of options have just changed? Or the selected value?
If the list of values have just changed then I need to reconstruct the select2, an set the controls value to null (otherwise the first item is selected by default). If the user just selected an item in the list, then I don't really want to do anything. Definitely not reconstruct the entire control or set the controls vale to null. But I can not find any way to see which values have changed.
Each observable in Knockout has subscribe methood, so if u have
var myProp = ko.observable();
u can subscribe for changes of this prop and do all nessesary things there:
myProp.subscribe(function(newValue){
console.log("value of prop changed to " + newValue);
});
We did implement custom select binding for jquery chosen plugin in following way:
ko.bindingHandlers.chosen =
{
init: function (element, valueAccessor, allBindings) {
var values = valueAccessor(),
$element = $(element);
$element.chosen(ko.toJS(values));
if (ko.isObservable(values.enable)) {
values.enable.subscribe(function (value) {
$element.prop('disabled', !value).trigger("chosen:updated");
});
}
// trigger chosen:updated event when the bound value or options changes
['value', 'selectedOption', 'options'].forEach(function (e) {
var bv = allBindings.get(e);
if (ko.isObservable(bv))
bv.subscribe(function () { $(element).trigger('chosen:updated'); });
});
var prop = allBindings.get('value');
$element.off('change');
$element.on('change', function (obj, event) {
if (!event || !prop) {
return;
}
if (typeof (prop()) == "number" && !isNaN(Number(event.selected))) {
prop(Number(event.selected));
} else {
prop(event.selected);
}
});
},
update: function (element) {
$(element).trigger('chosen:updated');
}
};