开发者

Hot-wiring/bootstrapping jQuery's constructor

Is there any way to hot-wire (or bootstrap, if you will) jQuery's constructor, in order to implement functionality in-front of it's default functionality. For instance; say I want to implement automatic caching...

Peudo-code alert!

var _init = $.init;

var cache = [];

// override jQuery's init function (the function that gets executed when
// you query the DOM
$.init.prototype = function (selector, context, rootjQuery)
{
    // if whatever selector is run, is not in the cache; cache it, using
    // the "old" init function
    if (!cache[selector]) ca开发者_JS百科che[selector] = _init(selector, context, rootjQuery);

    // return cached instance
    return cache[selector];
}

I know that this will break on elements that are updated dynamically and what not. The aim here is a crude implementation, which is going to be locked away in a dark corner somewhere. I also acknowledge that this is against all common sense. But humour me :)


What you want is jQuery.sub().

It allows to make a new copy of jQuery and overwrite those methods and properties without breaking the global jQuery.

If you must you can inject this subclass of jQuery back into global scope.

(function() {
    var $$ = jQuery.sub();

    $$.fn.init = function() {

        var obj = $.apply(null, arguments);
        console.log("object: ", obj);
        return obj;
    };

    $$(function() {
        // do stuff with overwritten jQuery.
        $$("div");
    });

})();

live example.

It's best to just make a factory that returns jQuery objects since jQuery has too many closures going on and you really need to know exactly what's going on or it will break.

The second object logged is indeed the document and thats from the $$(f) call since the selector becomes the document when you use jQuery as a ready handler.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜