javascript Knockout.JS 可观察数组更改为单个可观察项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9726172/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Knockout.JS Observable Array Changes to Individual Observable Items
提问by arb
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:
我有一个带有observableArray
(名为“所有”)对象的视图模型。该对象的属性之一是observable
选择的名称。我想要一些代码在数组中子对象的选定属性发生更改时执行。我尝试手动订阅all
viaall.subscribe()
但该代码仅在添加或删除项目时触发。我更新了代码以这样做:
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?
这是正确的方法还是有更好的方法?
回答by Domenic
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:
这接近正确。Observable 数组订阅仅用于添加或删除项目,而不是修改。所以如果你想订阅一个项目本身,你需要订阅这个项目本身:
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.
关键点:observableArray 跟踪哪些对象在数组中,而不是这些对象的状态
简单地将一个对象放入 observableArray 并不能使该对象的所有属性本身都是可观察的。当然,如果您愿意,您可以使这些属性可观察,但这是一个独立的选择。observableArray 只跟踪它持有哪些对象,并在添加或删除对象时通知侦听器。
(来自淘汰赛文档)
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
.
我说“接近正确”,因为您将要删除所有旧订阅。目前,如果 observable 数组在[a, b]
您订阅 时开始[a, b]
,但是如果c
被添加,您有两个订阅a
和b
一个订阅c
。