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

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

问题描述

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

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?

推荐答案

这接近正确.Observable 数组订阅仅用于添加或删除项目,而不是修改.因此,如果您想订阅某个项目本身,那么您需要订阅该项目本身:

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 被添加您有两个订阅 ab 加上一个订阅 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天全站免登陆