jqueryoverridingextending

Usefulness of extending jQuery core


I discovered a method of extending the core jQuery init function (which is what gets called anytime you use the $() or jQuery() function). This is not possible using the ordinary proxy pattern but the following code makes it work:

var origInit = jQuery.fn.init;

jQuery.fn.init = function(selector, context, rootjQuery) {
    if (some condition) {
        //custom code here, possibly returning some other jQuery object than
        //what jQuery would normally return
    }
    return origInit.call(jQuery.fn, selector, context, rootjQuery);
}

My question is where this might be useful, since I realized my initial intent of using it for caching of selectors was problematic (since it would affect the behavior of other plugins -- I ended up using a separate function for caching).

So I thought I'd share the method and I'm also curious to hear other ideas for potential uses of it. I thought maybe it could be used to support custom selectors of some kind, although I'm not sure when exactly that would be needed since jQuery already offers a lot of selectors.


Solution

  • You will find that jQuery has a method build around this concept.

    jQuery.sub()

    This allows you to extend jQuery locally without "corrupting" or "altering" the global jQuery object.

    From personal experimentation I find that jQuery is too complex to alter the init function without dealing with all kinds of nasty edge cases. It's far better to create a factory decoration method around the jQuery object.

    There are many uses for changing jQuery methods or the constructor ranging from logging to injecting custom logic like writing a GUID onto jQuery objects.