I try to remove a sub-tree ( at least one node ) from a tree, so I build a recursive function :
function remove(i)
{
tree = $('#jstree-tree').jstree(true).get_json('#', {flat:true});
j=0;
console.log(tree);
while(j<tree.length)
{
if(tree[i].id == tree[j].parent)
{
remove(j);
j--;
}
j++;
}
tree.splice(i,1);
}
but the problem here is the Recursion is stopped after the first call, I don't know why this my code.
Now j
is a global variable because of declaration without var
.
Thefore the value of j
is affected other executions of remove()
.
Changing j=0;
to var j=0;
fix this problem, but it cause infinit loop.
It seems that the recursion of remove()
is blocking the reflection of tree
value to $('#jstree-tree')
.
To avoid this issue, do tree = ...get_json(...)
at the out side of the recursion and reuse it.
This is working code:
function remove(arg)
{
tree = $('#jstree-tree').jstree(true).get_json('#', {flat:true});
var _remove = function (i) {
var j = 0;
while(j < tree.length)
{
if(tree[i].id == tree[j].parent)
{
_remove(j);
j--;
}
j++;
}
tree.splice(i,1);
}
_remove(arg);
}