在淘汰赛观察到的阵列订阅功能,你可以决定添加或移除哪些元素? [英] In a Knockout observable array subscription function, can you determine what elements were added or removed?

查看:110
本文介绍了在淘汰赛观察到的阵列订阅功能,你可以决定添加或移除哪些元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

淘汰赛的观测阵列给你订阅,以改变阵列的功能,< A HREF =htt​​p://knockoutjs.com/documentation/observables.html相对=nofollow>就像任何其他可观察。 订阅回调函数接收一个参数,它的的新的的数组的值。下面是一个例子(和小提琴):

Knockout's Observable Arrays give you the ability to "subscribe" to changes to the array, just like any other observable. The "subscribe" callback function receives one argument, and it's the new value of the array. Here's an example (and fiddle):

var oa = ko.observableArray(['some','initial','data']);

oa.subscribe(function(newValue){
    console.log("Array was updated! Now it's:");
    console.log(newValue);
    // But which item was added?
});

oa.push("more data!");
setTimeout(function(){
    oa.remove("some");
},1500);

不过,我想知道,得到了添加到观察的数组元素是什么。有没有办法做到这一点?如果我可以在旧数组比较新数组,然后我可以决定哪些项目(S)添加或删除。但似乎在订阅功能的回调被调用的时候,有没有办法进入previous数组值。在那儿?

However, I would like to know what element got added to the observable array. Is there any way to do this? If I could compare the old array to the new array, then I could determine which item(s) were added or removed. But it seems that by the time the "subscribe" function callback is called, there is no way to access "previous" array values. Is there?

推荐答案

淘汰赛observableArray提供事件 arrayChange

knockout observableArray provides event arrayChange.

oa.subscribe(function(changes){
    ko.utils.arrayForEach(changes, function(c) {
        console.log(c.status + " value:\"" + c.value + "\" at index:" + c.index);
    });
}, null, 'arrayChange');

http://jsfiddle.net/huocp/Vf8RK/3/

这篇关于在淘汰赛观察到的阵列订阅功能,你可以决定添加或移除哪些元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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