How does knockout custom binding work with observableArray? When using ko.observable() with custom binding, everything works as expected. When using ko.observableArray(), on
You will want to create a dependency on your observableArray within your custom binding. So, at the very least something like:
ko.bindingHandlers.updateBinding = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
alert("Binding Handler (Init)");
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
//create a dependency, normally you would do something with 'data'
var data = ko.utils.unwrapObservable(valueAccessor());
alert("Binding Handler (Update)");
}
};
The reason that this works with your observable example is because all bindings on a single element are triggered together (more info here).
The reason that this does not behave the same way on your other binding is that foreach
behaves differently. Changes to the observableArray do not trigger the foreach
binding directly (or the whole section would be re-rendered). Instead it triggers logic in a separate ko.computed that evaluates how the array has changed and makes the necessary incremental updates (add an item, remove an item, etc.).