简体   繁体   English

KnockoutJS:在订阅回调中修改可观察数组时进行无限递归

[英]KnockoutJS: Infinite recursion while modifying observable array within the subscription callback

I can't figure out why the following code snippet leads to infinite recursion: 我不明白为什么下面的代码片段会导致无限递归:

var observableArray = ko.observableArray();
observableArray.subscribe(function (changes) {
    changes.forEach(function(change) {
        console.log("change: " + JSON.stringify(change));
        if (change.status === 'added') {
            if (change.value === "first") {
                observableArray.push("second");
            }
        }
    });
}, null, "arrayChange");

observableArray.push("first");

And here is the console log: 这是控制台日志:

change: {"status":"added","value":"first","index":0}    
change: {"status":"added","value":"first","index":0}  
change: {"status":"added","value":"first","index":0}  
change: {"status":"added","value":"first","index":0}  
change: {"status":"added","value":"first","index":0}  
...  
Uncaught RangeError: Maximum call stack size exceeded  

I really don't get what is going on here. 我真的不明白这里发生了什么。 Could anyone help me, please? 有人可以帮我吗?

This looks like logical mistake 这看起来像是逻辑错误

var observableArray = ko.observableArray();
 console.log(changes);  //Add log here
observableArray.subscribe(function (changes) {
    changes.forEach(function(change) {
        console.log("change: " + JSON.stringify(change));
        if (change.status === 'added') {
            if (change.value === "first") {
                observableArray.push("second");
            }
        }
    });
}, null, "arrayChange");

observableArray.push("first"); 

As per your logic of subscribe you do not want to add "first" value if it is already there. 根据您的订阅逻辑,如果已经存在“ first”值,则不想添加。 But that "first" value is always going to be there in your observable array. 但是,该“第一个”值将始终存在于可观察数组中。 Add console log as I have added in above code. 添加控制台日志,就像我在上面的代码中添加的一样。

Now this is what you will see output like 现在这就是您将看到的输出

在此处输入图片说明

You have added observableArray.push("second"); 您已经添加了observableArray.push(“ second”); but, in that same observable array "first" is always there and code will keep adding "second" and your code will result into call stack size exceeded. 但是,在同一可观察数组中,“ first”始终存在,并且代码将继续添加“ second”,并且您的代码将导致超出调用堆栈的大小。

I think you need to change the logic to add if "first" element is there in the array then do not insert it like break operation or something like that. 我认为,如果数组中存在“第一个”元素,则需要更改添加的逻辑,然后不要像中断操作或类似操作那样插入它。

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

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