19

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?

arb
  • 7,753
  • 7
  • 31
  • 66

1 Answers1

20

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:

Key point: An observableArray tracks which objects are in the array, not the state of those objects

Simply putting an object into an observableArray doesn’t make all of that object’s properties themselves observable. Of course, you can make those properties observable if you wish, but that’s an independent choice. An observableArray just tracks which objects it holds, and notifies listeners when objects are added or removed.

(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 if c gets added you have two subscriptions for a and b plus one for c.

Community
  • 1
  • 1
Domenic
  • 110,262
  • 41
  • 219
  • 271
  • If I blow away the old array with `all([])`, will that kill all the subscriptions? The user doesn't really directly interact with this collection, it's for like a collection of check boxes and not dynamically changed. – arb Mar 15 '12 at 18:55
  • Why is it an observable array at all then? Just make it a normal array that contains objects with observable properties. – Domenic Mar 15 '12 at 18:56
  • To actually answer your question though: no, it will not. Subscriptions only are disposed by calling `subscription.dipose()`, as seen at the bottom of http://knockoutjs.com/documentation/observables.html – Domenic Mar 15 '12 at 18:57
  • Because it gets filled via an AJAX call and I want the DOM to update when the AJAX call comes back. – arb Mar 15 '12 at 18:58
  • 1
    Then just make it a regular observable that happens to contain an array; don't make it an observable array. – Domenic Mar 15 '12 at 18:58