jsTree is great, but its documentation is pretty tight. In the end, I realized that this is a solution for everyone who works in this topic.
First, you need to bind the open_node event to the tree in question. Something along the lines
$("tree").jstree({"themes":objTheme,"plugins":arrPlugins,"core":objCore}). bind("open_node.jstree",function(event,data){closeOld(data)});
i.e. you set up a treeview instance and then bind the open_node event. Here I call the closeOld function to perform the required task - close any other node that may be open. The function looks like this:
function closeOld(data) { var nn = data.rslt.obj; var thisLvl = nn; var levels = new Array(); var iex = 0; while (-1 != thisLvl) { levels.push(thisLvl); thisLvl = data.inst._get_parent(thisLvl); iex++; } if (0 < ignoreExp) { ignoreExp--; return; } $("#divElements").jstree("close_all"); ignoreExp = iex; var len = levels.length - 1; for (var i=len;i >=0;i--) $('#divElements').jstree('open_node',levels[i]); }
This will correctly handle collapsing all other nodes regardless of the nesting level of the node that has just been expanded.
A brief explanation of the steps taken
- First, we take a step back up the tree structure until we reach the top level of the node (-1 in jstree speak), making sure that we record every node ancestor encountered in the process in the level array
- Then we collapse all nodes in the treeview
- Now we are going to redeploy all the nodes in the levels array. At the same time, we do not want this code to run again. To stop this, we set the global variable ignoreEx to the number of nodes in the levels
- Finally, we go through the nodes in the levels and expand each of them.
source share