I have a view model with an observableArray
(named 'all') of objects. One of the properties of that object is an observable
name selected. I want some code to execute whenever the selected property of the of the child object in the array changes. I tried manually subscribing to all
via all.subscribe()
but that code only fires when items are added or removed. I updated the code to do it like this:
all.subscribe(function () {
ko.utils.arrayForEach(all(), function (item) {
item.selected.subscribe(function () {
//code to fire when selected changes
});
});
});
Is this the right way to do this or is there a better way?
This is close to correct. Observable array subscriptions are only for when items are added or removed, not modified. So if you want to subscribe to an item itself, you'll need to, well, subscribe to the item itself:
(from Knockout documentation)
I say "close to correct" since you will want to remove all the old subscriptions. Currently, if the observable array starts as
[a, b]
you are subscribing to[a, b]
, but then ifc
gets added you have two subscriptions fora
andb
plus one forc
.