Search code examples
javascriptjstree

Jstree: override function for paste


I use copy and paste in my Jstree instance but the default paste clears the copied nodes while I want to keep these in the buffer. If I modify te source code no problem but I'd rather not do that.

paste : function (obj, pos) {
            obj = this.get_node(obj);
            if(!obj || !ccp_mode || !ccp_mode.match(/^(copy_node|move_node)$/) || !ccp_node) { return false; }
            if(this[ccp_mode](ccp_node, obj, pos, false, false, false, ccp_inst)) {
                /**
                 * triggered when paste is invoked
                 * @event
                 * @name paste.jstree
                 * @param {String} parent the ID of the receiving node
                 * @param {Array} node the nodes in the buffer
                 * @param {String} mode the performed operation - "copy_node" or "move_node"
                 */
                this.trigger('paste', { "parent" : obj.id, "node" : ccp_node, "mode" : ccp_mode });
            }
            // what I changed by commenting out, need the buffer later
            // ccp_node = false;
            // ccp_mode = false;
            // ccp_inst = false;
        },

How can I override this function without modifying the source code ?

Here is a jsfiddle to demonstrate what I tried.


Solution

  • Found it myself. Updated the fiddle. I'll leave the question unanswered for the moment in case someone has a better solution.

    Here is the code

        $.jstree.core.prototype.paste = function (obj, pos) {
            // need buffer otherwise ccp vars not known
            var buffer = this.get_buffer();
            ccp_mode = buffer.mode;
            ccp_node = buffer.node;
            ccp_inst = $('#jstree').jstree(true)
            obj = this.get_node(obj);
            if(!obj || !ccp_mode || !ccp_mode.match(/^(copy_node|move_node)$/) || !ccp_node) { return false; }
            if(this[ccp_mode](ccp_node, obj, pos, false, false, false, ccp_inst)) {
              this.trigger('paste', { "parent" : obj.id, "node" : ccp_node, "mode" : ccp_mode });
            }
          }