最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Knockout.JS Observable Array Changes to Individual Observable Items - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question asked Mar 15, 2012 at 18:47 arbarb 7,8637 gold badges34 silver badges67 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 19

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.

发布评论

评论列表(0)

  1. 暂无评论