Apr 02, 2012
- 2012-04-02 18:00
$ = undefined;
We have now saved a reference to $ into $j, so that we can use $j for jQuery functionality. $j("p.myClass").removeClass("myClass"), for example. We've accomplished the basic goal, but we can do better.
A few of issues with our first attempt:
- If $ was pointing at anything before jQuery used it (like another library), that reference has been lost.
- In the case of juggling multiple versions of jQuery (not something I would recommend), the last imported version will overwrite the former's jQuery variable.
- Just for the sake of best practices, we should use jQuery's built-in noConflict() function, in case they add additional handling in later releases.
Thankfully, when jQuery is imported, it saves a reference to any existing $ into a private variable, called _$. Calling jQuery.noConflict() will not only reset $, it will return it to its pre-jQuery value. Another nice bonus is that the noConflict() function returns a reference to jQuery object itself. This allows us to combine the two lines, into simply "var $j = $.noConflict();"
One last note, about the argument sent to noConflict(). It defaults to false, but you can pass a boolean value, which instructs jQuery whether to release jQuery. This is safe to do, as long as we remember to use our shorthand variable in ALL cases. $j is a substitute for any reference to the jQuery object, so "jQuery.parseJSON(jsonString);" can be written as "$j.parseJSON(jsonString);"