Search code examples
javascriptrootjstreechildrendestroy

Deleting root nodes in jstree detaches event listeners


I want to recreate the jstree by deleting all the root nodes and reading back the structure by using ajax. If I use:

$("#tree").jstree("destroy");

and then recreate the jstree instance:

$("#tree").jstree({ "core": {"check_callback" : true} });

it draws a new jstree. I add the json information coming from the ajax, but the event listeners don't work any more when I click on the root nodes.

This is the workaround routine that works:

var ref = $("#tree").jstree(true);          // get an existing instance
var nodes = ref.get_node("#").children; // -1 didn't work, so I used "#"
while (nodes.length > 0){
  ref.delete_node(nodes[0]);
}

Is there any parameter that I am missing with the "destroy" method that will allow the event listeners connect back with the new jstree instance ?


Solution

  • No, that's not possible, since the destroy function "remove all traces of jstree from the DOM and destroy all instances" (jstree documentation): that means that the jquery objects composing the jstree are actually removed and they take with them all the event listeners.

    I don't know what you want to accomplish but if you need to use destroy, you will have to re-add all the listeners once again after recreating the tree.

    Otherwise you should try to find a non-destructive way of doing your stuff, there usually is one, the nuke option is never a really good idea apart from very few cases.