给定一棵树中的(父)节点,我需要检索[1]父项下的孩子数加上父项的孩子下的父项加上父级的孩子的子项,依此类推[2]从[1]中被标记的孩子数“打开”。
我的测试数据有一个父母,其中有两个孩子。我的方法-
Meteor.methods({
...
'getSubCounts': function(selectedNodeId){
var children = ItemList.find({"parent.parentid": selectedNodeId}).fetch();
var numChildren = children.length;
console.log("Number of children of " + selectedNodeId + ": " + numChildren);
var openChildrenCount = children.filter(function(row) {
return (row.status === "OPEN");
}).length;
for (i = 0; i < numChildren; i++) {
console.log("iterations for child " + i + ": " + children[i]._id);
Meteor.call('getSubCounts', children[i]._id, function(error, result) {
if(error) {
console.log("error occured during iteration " + error);
} else {
numChildren = numChildren + result.numChildren;
openChildrenCount = openChildrenCount + result.openChildrenCount;
}
});
}
return {numChildren: numChildren, openChildrenCount: openChildrenCount};
},
...
});
我正在调用客户端帮助程序-
'subcounts': function(){
if (this._id != null) {
Meteor.call('getSubCounts', this._id, function(error, result) {
if(error) {
// nothing
} else {
Session.set('subcountsdata', result)
}
});
在(浏览器)输出中,第一个孩子看起来像预期的那样进行迭代,但是第二个孩子陷入了无限循环。 (请注意,父节点ID为8veHSdhXKjyFqYZtx
,子ID为iNXvZGaTK3RR6Pekj,C6WGaahHrPiWP7zGe
)
Number of children of 8veHSdhXKjyFqYZtx: 2
iterations for child 0: iNXvZGaTK3RR6Pekj
Number of children of iNXvZGaTK3RR6Pekj: 0
iterations for child 1: C6WGaahHrPiWP7zGe
Number of children of C6WGaahHrPiWP7zGe: 0
iterations for child 1: C6WGaahHrPiWP7zGe
Number of children of C6WGaahHrPiWP7zGe: 0
iterations for child 1: C6WGaahHrPiWP7zGe
Number of children of C6WGaahHrPiWP7zGe: 0
iterations for child 1: C6WGaahHrPiWP7zGe
Number of children of C6WGaahHrPiWP7zGe: 0
....
为什么在这种情况下第二次迭代无限发生?看来是由于反应性造成的,但我不太了解实际原因。
答案 0 :(得分:2)
很可能您只是在方法函数中缺少var i
。
在不将i
声明为局部变量的情况下,您使用全局范围变量,每次调用方法时,该变量都会重新分配为0。
顺便说一句:
ReactiveVar
并仅在必要时进行呼叫,通常是在Blaze模板生命周期挂钩(如onCreated)或事件侦听器中进行。