Knockout.JS可观察数组对单个可观察项目的更改 [英] Knockout.JS Observable Array Changes to Individual Observable Items

查看:96
本文介绍了Knockout.JS可观察数组对单个可观察项目的更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有 observableArray (名为all)对象的视图模型。该对象的一个​​属性是选择了 observable 名称。我想要一些代码在数组中子对象的selected属性发生变化时执行。我尝试通过 all.subscribe()手动订阅所有但该代码仅在添加或删除项目时触发。我更新了这样的代码:

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:


关键点:observableArray跟踪数组中的对象,而不是那些对象的状态

简单地将对象放入observableArray并不能全部该对象的属性本身是可观察的。当然,如果您愿意,您可以观察这些属性,但这是一个独立的选择。 observableArray只跟踪它所拥有的对象,并在添加或删除对象时通知侦听器。

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.

来自Knockout文档

我说接近正确因为您要删除所有旧订阅。目前,如果可观察数组以 [a,b] 开头,则您订阅 [a,b] ,但然后,如果添加 c ,您有两个订阅 a b 加一个 c

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.

这篇关于Knockout.JS可观察数组对单个可观察项目的更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆