仅为新的或删除的条目订阅可观察数组 [英] Subscribe to observable array for new or removed entry only

查看:141
本文介绍了仅为新的或删除的条目订阅可观察数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以是的我可以订阅一个可观察的数组:

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屋!

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