在Knockout可观察数组订阅函数中,您可以确定添加或删除了哪些元素吗?

Jos*_*osh 3 javascript arrays knockout.js

Knockout的Observable Arrays使您能够"订阅"数组的更改,就像任何其他可观察的一样."subscribe"回调函数接收一个参数,它是数组的值.这是一个例子(和小提琴):

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);
Run Code Online (Sandbox Code Playgroud)

但是,我想知道哪些元素被添加到observable数组中.有没有办法做到这一点?如果我可以将旧数组与新数组进行比较,那么我可以确定添加或删除了哪些项目.但似乎在调用"subscribe"函数回调时,无法访问"previous"数组值.在那儿?

huo*_*ocp 6

knockout observableArray提供活动arrayChange.

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

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