Search code examples
javascriptjqueryjqtree

Access variable from 1 .js source file (jqTree), from within different .js file, to override method


(new to JS, jQuery, & jqTree)

I am trying to override a method (JqTreeWidget.prototype.openNode) from one .js file (tree.jquery.js) in another (my own custom.js).

I've read that to override a js method in general, I just need to redefine it. So I am trying to do that on the method, and I think I am stuck on accessing the variable that has the original method (JqTreeWidget). I think the challenge is that the original method is in tree.jquery.js (source) that is separate from my own other custom.js file where I want to do the override.

The goal of this Question would be to allow me to write something like this in my custom.js (<reference to JqTreeWidget.prototype.openNode> would be the Answer to this Question):

var originalMethod = <reference to JqTreeWidget.prototype.openNode>;

// Override of originalMethod
<reference to JqTreeWidget.prototype.openNode> = function( node, slide ){
    // my code I want to happen 1st here
    changeAncestorHeightRecursively( node, true);

    // my code is done, and now I'm ready to call the original method
    originalMethod.call( this, node, slide );
}

I think that would be the most non-intrusive way to do the override, without actually hacking in to the tree.jquery.js source.

See my custom.js at http://codepen.io/cellepo/pen/LGoaQx The separate source tree.jquery.js is added externally in the JS settings of that codepen.

How can I get access (from within my custom.js file) to JqTreeWidget variable that is in the source file (tree.jquery.js)? Is it even possible? Is JqTreeWidget not in scope outside of tree.jquery.js, or is it not a global variable? I was hoping treeContainer.tree.prototype would have it, but I haven't had luck so far...

Thanks!


Solution

  • The prototype object can be obtained via:

    jQuery.fn.tree("get_widget_class").prototype
    

    Note that this is not a generalized solution for any jQuery plugin. This is something explicitly implemented by the tree plugin.