noConflict mechanism in jQuery

  sonic0002        2013-03-14 19:40:36       4,425        0    

Many JavaScript frameworks like to use $ as function or variable name, jQuery is one of them. In jQuery, $ is just a reference to window.jQuery, so even if $ is deleted, window.jQuery will still be available to ensure the whole library can work normally. jQuery API design takes fully consideration of multiple frameworks conflicts, we can use jQuery.noConflict function to easily handle control.

jQuery.noConflict accepts one optional boolean parameter[1] to determine whether to hand jQuery object itself when handing the $ reference.

jQuery.noConflict([removeAll])

By default, when executing noConflict, the control of $ variable will be handed over to the first library which has the $ variable, when removeAll is true, when executing noConflict, $ and jQuery will be handed over to the first library which contains them.

For example, when mixing KISSY and jQuery, and if you are used to us $=KISSY to simplify API, you can use noConflict to solve the conflict issue.

Then how does this mechanism work? While reading the beginning of jQuery source code[2], the first thing it does is:

        // Map over jQuery in case of overwrite
        _jQuery = window.jQuery,

        // Map over the $ in case of overwrite
        _$ = window.$,

It's easy to understand that jQuery uses two private variables to map jQuery and $ in window object to prevent variables being overwritten. Once noConflict is called, then the control will be handed over depending on the differences among _jQuery,_$,jQuery,$. The detail codes are:

noConflict: function( deep ) {
                if ( window.$ === jQuery ) {
                        window.$ = _$;
                }

                if ( deep && window.jQuery === jQuery ) {
                        window.jQuery = _jQuery;
                }

                return jQuery;
        }

If deep is not set, _$ will overwrite window.$, then the alias of jQuery $ will lose its effect, but jQuery itself will not be affected. If other libraries or codes redefines $, then its control will be completed handed over. Otherwise if deep is set to true, _jQuery will overwrite window.jQuery, then $ and jQuery will both lose effect.

But one fact is that some plug-ins may not work properly with this function. We can recover the $ alias using some simple method:

var query = jQuery.noConflict(true);
(function ($) {

     // Plug-ins or other codes

})(query);

[1] http://api.jquery.com/jQuery.noConflict/#jQuery-noConflict-removeAll
[2] https://github.com/jquery/jquery/blob/master/src/core.js

Source : http://ued.taobao.com/blog/2013/03/jquery-noconflict/

JQUERY  NOCONFLICT  $ 

       

  RELATED


  0 COMMENT


No comment for this article.



  RANDOM FUN

http vs https