Search code examples
javascriptjstreejstree-dnd

jsTree determine move between trees and change copied node ID


I'm trying to use jsTree to create 2 trees, based on parent-child relationships. To do this, I use the following script:

$(function () {

   loadTree($('#jstree_indexed_container'), document.getElementById('hiddenFieldIndexedData').value);
   loadTree($('#jstree_nonindexed_container'), document.getElementById('hiddenFieldNonIndexedData').value);

});

function loadTree(jsTreeContainer, stringData) {

   jsTreeContainer.jstree({

      "core": {
         "animation": 0,
         "check_callback": true,
         "themes": { "stripes": true },
         'data': JSON.parse(stringData)
      },
      "plugins": ["contextmenu", "dnd", "search", "wholerow", "unique"]

   });

   jsTreeContainer.on("move_node.jstree", function (e, data) {
      notifyServerOfChange(data, false);
   });

   jsTreeContainer.on("copy_node.jstree", function (e, data) {
      notifyServerOfChange(data, true);
   });

}

function notifyServerOfChange(data, isCopy) {
   var oldParent = getNodeById(data.old_instance, data.old_parent);
   var newParent = getNodeById(data.new_instance, data.parent);

   alert(sprintf("%s node %s from %s to %s. It now has ID: %s", (isCopy ? "Copied" : "Moved"), (data.original != null ? data.original.id : data.node.id), getNodeTitle(oldParent), getNodeTitle(newParent), data.node.id));
}

function getNodeById(jsTreeContainer, id) {
   return jsTreeContainer.element.find("[id='" + id + "']");
}

function getNodeTitle(node) {
   return node.find('a').first().text();
}

However, when moving a node between the 2 trees, the "copy_node.jstree" event is always invoked, even though I'm moving the node. If I move the node in the same tree, I get the correct "move_node.jstree" event.

Question 1: Is there a way of correctly determining if the node was moved, rather than copied, between 2 trees?

Question 2: My node IDs are computed based on the parent-child relationship, so after copying / moving a node, I recompute this relationship and I want to use it to replace the previous ID of the node. If I try to modify the data.node.id in the notifyServerOfChange method, the node can no longer be selected afterwards.

Thank you


Solution

  • If you move nodes between trees with drag n drop (as it goes from the plugins you use) you can listen to dnd_stop.vakata event and check if ctrl key is pressed like this:

    $(document).on('dnd_stop.vakata', function (e, data) {
        if (data.event.ctrlKey) {
            console.log('copy');
        } else {
            console.log('move');
        }
     });
    

    Check fiddle: JS Fiddle