Search code examples
jstree

jsTree cancel Create node


I'm using context menu is jsTree and here's my code:

"contextmenu" : {
    "items": function ($node) {
        return {
            "create": {
                "separator_before": false,
                "separator_after": false,
                "label": "Créer",
                "action": function (data) {
                    var inst = $.jstree.reference(data.reference),
                        obj = inst.get_node(data.reference);
                    inst.create_node(obj, {}, "last", function (new_node) {
                        new_node.type = "child";
                        setTimeout(function () {
                            inst.edit(new_node);
                        }, 0);
                    });
                }
            },
            "Rename": {
                "separator_before": false,
                "separator_after": false,
                "label": "Renommer",
                "action": function (data) {
                    var inst = $.jstree.reference(data.reference),
                        obj = inst.get_node(data.reference);
                    inst.edit(obj);
                }
            },
            "Remove": {
                "separator_before": false,
                "separator_after": false,
                "label": "Supprimer",
                "action": function (data) {
                    var inst = $.jstree.reference(data.reference),
                        obj = inst.get_node(data.reference);
                    inst.delete_node(obj);
                }
            }
        };
    }
},

If I am renaming a node and I decide to cancel it, I just press the escape button and the node returns to its previous name.

If I want to create a node, it creates the node first and put it into editing mode. Now if I press escape, the editing mode is exited but the node remains. What I want to accomplish is if I'm in creation mode, and I press escape, it should remove the newly created node.

Any ideas on how I can do this?


Solution

  • The node edit function itself accepts a callback as a second argument. The callback function when called, receives a boolean flag indicating if the user cancelled the edit.

    inst.edit(new_node,"New node",function(node,bStatus,bCancelled){
        if(bCancelled){
            this.delete_node(node);
        }
    });
    

    The current node and the instance is also returned which can be used to delete the node.

    Reference: https://www.jstree.com/api/#/?q=edit