仅为新的或删除的条目订阅可观察数组 [英] Subscribe to observable array for new or removed entry only
问题描述
所以是的我可以订阅一个可观察的数组:
So yes I can subscribe to an observable array:
vm.myArray = ko.observableArray();
vm.myArray.subscribe(function(newVal){...});
问题是 newVal
传递给function是整个数组。无论如何我只能得到三角洲部分?说添加或已删除元素?
The problem is the newVal
passed to the function is the entire array. Is there anyway I can get only the delta part? Say the added or removed element?
推荐答案
从KnockoutJS 3.0开始,ko.observableArray上有一个 arrayChange订阅选项。
As of KnockoutJS 3.0, there's an arrayChange subscription option on ko.observableArray.
var myArray = ko.observableArray(["Alpha", "Beta", "Gamma"]);
myArray.subscribe(function(changes) {
// For this example, we'll just print out the change info
console.log(changes);
}, null, "arrayChange");
myArray.push("newitem!");
在上面的回调中,changes参数将是一个更改对象数组,如下所示:
In the above callback, the changes argument will be an array of change objects like this:
[
{
index: 3,
status: 'added',
value: 'newitem!'
}
]
针对您的具体问题,您希望收到有关新项目或已删除项目的通知。要使用Knockout 3实现它,它看起来像这样:
For your specific problem, you want to be notified of new or removed items. To implement that using Knockout 3, it'd look like this:
myArray.subscribe(function(changes) {
changes.forEach(function(change) {
if (change.status === 'added' || change.status === 'deleted') {
console.log("Added or removed! The added/removed element is:", change.value);
}
});
}, null, "arrayChange");
这篇关于仅为新的或删除的条目订阅可观察数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!