Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery's noConflict: Just a quick thought

The documentation says you can use $.noConflict() like this:

jQuery.noConflict();
(function($) { 
  $(function() {
    // more code using $ as alias to jQuery
  });
})(jQuery);
// other code using $ as an alias to the other library

It also states that calling it returns an instance of the jQuery object, so I could do this:

jQuery.noConflict()(function(){
    // code using jQuery
}); 
// other code using $ as an alias to the other library

However, is this combination valid?

(function($) { 
  $(function() {
    // more code using $ as alias to jQuery
  });
})(jQuery.noConflict());
// other code using $ as an alias to the other library

If so, is there a reason to not do it this way? And also (if it works), why not always use this method to guarantee that inside of our closure, $ == jQuery?

like image 212
JesseBuesking Avatar asked Nov 23 '11 16:11

JesseBuesking


2 Answers

The last method works as well - jQuery.noConflict() returns the jQuery object, which is passed as the $ argument to the function.

I don't see a reason to not do it that way and would prefer it to the other methods.

like image 146
Otto Allmendinger Avatar answered Sep 20 '22 01:09

Otto Allmendinger


I don't see why not since jQuery.noConflict returns the jQuery object and it's evaluated before the function is called.

like image 30
Artefacto Avatar answered Sep 19 '22 01:09

Artefacto