I have a knockout model which has multiple observable properties:
var personViewModel = {
name: ko.observable('Bob'),
age: ko.observable(123)
};
I would like to create a custom binding which renders person view model. However, I would like this binding to update if any of the child properties, i.e. name
or age
, are updated.
With a bindingHandler the update method is only fired when the bound observable property is updated, not when a child property on the bound observables change.
As a workaround I am adding subscriptions to the child properties in the init
function:
ko.bindingHandlers.foo = {
init: function (element, valueAccessor, allBindingsAccessor,
viewModel, bindingContext) {
// setup code goes here ... DOM elements inserted etc....
valueAccessor().age.subscribe(function () {
// Update the UI
});
valueAccessor().name.subscribe(function () {
// Update the UI
});
},
update: function (element, valueAccessor, allBindingsAccessor,
viewModel, bindingContext) {
// Update the UI
}
};
NOTE: this is a simplified example, I do have a generic approach for subscribing to multiple child observables!
Is this a good way to approach the problem? Or is there some built-in Knockout feature that I am overlooking here?