I’ve been writing JavaScript and utilizing the jQuery library for a good 7 years now. I’ve recently come across a situation where I had to write code in a jQuery.noConflict() environment. This means the infamous $ jQuery shorthand that everyone loves was no longer available to me. That’s right, if I wanted to use anything in the jQuery library, I would have to type the word j-Q-u-e-r-y out every. single. time.
At first I decided to suck it up and go with using ‘jQuery’ instead of ‘$’ for a little bit for the sake of getting my code to work. However, after a while I felt like there was jQuery fungus growing in every corner of my code. I needed anti-jQuery-fungus cream quick and it had to come in the form of ‘$’.
However, the jQuery-fungus would not give up so easily. Due to the nature of my code, the fungus was able to grow deep into the very fabric and essence of objects and functions. I had been using the convention of JavaScript namespaces. For example, I had something along the lines of:
var rafiki = rafiki || {}; rafiki.myObject1 = {}; rafiki.myObject1.myFunction = function(foo, bar){return jQuery(foo).val + jQuery(bar).val() };
I prefer this convention as it feels more object-oriented-esque (it’s easier for me to organize my code) and I have easy access to my objects and functions via Chrome dev tools (i.e. autocomplete on the console).
All my objects and function within the rafiki namespace depend on jQuery. I wanted to change every single jQuery to ‘$’. There are various ways of achieving this without polluting the global namespace, such as wrapping your code in a closure:
(function($){ //codez })(jQuery)
This method is nice, and privatizes your code, but it removes all your capability of executing or debugging your code via the console as it just returns a function. You can use various debuggers and set break points, but I find this more tedious than just accessing your functions/objects directly from the console.
So, how can I achieve ‘$’ access, while at the same time not polluting the global namespace AND using JS namespace conventions AND having access to my objects and functions via console? After a little head bashing I came up with this little technique:
var myNameSpace = myNameSpace || {}; //declare your namespace first (function($){ myNameSpace.myObject1 = { function1: function(param){}, function2: function(param1, param2){}, ... } })(jQuery); //Add subsequent objects and functions inside closure
The trick to the code above is to add to extend your namespace inside closures that get fed the jQuery ‘$’ as a parameter. This achieves a few things: you can use JS namespace conventions, you’re not polluting the global namespace, you’re able to use the ‘$’ jQuery shorthand in a jQuery.noConfliction() environment, and you still have access to your objects/functions via the console!
Hope this helps folks out! Feel free to comment below for better strategies solutions that you have found from your JS adventures!
-Raf