订阅仅用于新条目或已删除条目的 observable 数组 [英] Subscribe to observable array for new or removed entry only

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

问题描述

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

vm.myArray = ko.observableArray();vm.myArray.subscribe(function(newVal){...});

问题是传递给函数的 newVal 是整个数组.无论如何我只能得到增量部分吗?说添加删除元素?

解决方案

从 KnockoutJS 3.0 开始,有一个 ko.observableArray 上的arrayChange订阅选项.

var myArray = ko.observableArray(["Alpha", "Beta", "Gamma"]);myArray.subscribe(function(changes) {//对于这个例子,我们将只打印出更改信息控制台日志(更改);}, null, "arrayChange");myArray.push("newitem!");

在上面的回调中,changes 参数将是一个像这样的 change 对象数组:

<预><代码>[{指数:3,状态:'添加',价值:'新项目!'}]

对于您的具体问题,您希望收到有关新项目或已删除项目的通知.要使用 Knockout 3 实现它,它看起来像这样:

myArray.subscribe(function(changes) {变化.forEach(功能(变化){if (change.status === 'added' || change.status === 'deleted') {console.log("添加或删除!添加/删除的元素是:", change.value);}});}, null, "arrayChange");

So yes I can subscribe to an observable array:

vm.myArray = ko.observableArray();
vm.myArray.subscribe(function(newVal){...});

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?

解决方案

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!");

In the above callback, the changes argument will be an array of change objects like this:

[ 
   { 
      index: 3, 
      status: 'added', 
      value: 'newitem!' 
   }
]

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");

这篇关于订阅仅用于新条目或已删除条目的 observable 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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