Usefulness of extending jQuery core

牧云@^-^@ 提交于 2020-01-15 03:20:25

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/5842475/usefulness-of-extending-jquery-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!