简体   繁体   English

复制2个可观察数组然后进行比较

[英]copying 2 observable arrays and then comparing

I have declared 2 observable arrays as following in my code 我在我的代码中声明了2个可观察的数组

self.versionDataByProduct = ko.observableArray([]);
self.copiedSavedVersionData = ko.observableArray([]);

When i save data i copy all value from self.versionDataByProduct into self.copiedSavedVersionData like below 当我保存数据时,我将self.versionDataByProduct中的所有值复制到self.copiedSavedVersionData中,如下所示

 self.copiedSavedVersionData(self.versionDataByProduct());

Then i try to compare 2 observable array on button event called compareArray like below 然后我尝试比较下面名为compareArray的按钮事件上的2个可观察数组

 this.compareArray = function () {
        debugger;
        var results = [];
        var differences = ko.utils.compareArrays(self.versionDataByProduct(), self.copiedSavedVersionData());
        ko.utils.arrayForEach(differences, function (difference) {
            if (difference.status === "deleted") {
                results.push(difference.value);
            }
        });
        return results;
    };

But this doesnt work. 但这不起作用。 Because after i copy one observable array to other and do some modification in observable array then it automatically updates other. 因为在将一个可观察数组复制到另一个并在可观察数组中进行一些修改之后,它会自动更新其他数组。 I dont want that. 我不想那样。 I want my observable array self.copiedSavedVersionData to remain as is after it is copied. 我希望我的可观察数组self.copiedSavedVersionData在复制后保持原样。 How can i achieve it? 我怎样才能实现它? I am just doing it track if i have done any changes. 如果我做了任何更改,我只是跟踪它。 If array is changed then i will enable button in my code. 如果更改了数组,那么我将在我的代码中启用按钮。 Currently i dont know how do i go about dirty tracking so found this alternative but not working. 目前我不知道如何进行脏跟踪,因此找到了这个替代但不起作用。 Please help. 请帮忙。

You can use slice function for this: 您可以使用slice功能:

 self.copiedSavedVersionData(self.versionDataByProduct().slice(0));

In that case ko will clone array. 在那种情况下,ko将克隆数组。

试试:

ko.utils.arrayPushAll(self.copiedSavedVersionData, self.versionDataByProduct());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM