Creating your own javascript namespaces with jQuery

on Monday, January 25, 2010

This isn’t cutting edge by a long shot, but if I had found a post on this a couple months ago it would have kept me from refactoring my code two or three times. One of the amazing things about working with jQuery is the programmers have dealt with every impossible situation you could imagine. And, when you look through their code you are given an insight into javascript best practices.

(function ($) {

if (!window.baseNamespace) { window.baseNamespace = {}; }
if (!baseNamespace.subNamespace) { baseNamespace.subNamespace = {}; }

var pseudoGlobal = 10;

$.extend(baseNamespace.subNamespace, {
someVariable: 10,

someFunction: function () {
alert(pseudoGlobal);
}
});

})(jQuery);

Unfortunately, this description doesn’t follow the exact same best practices that jQuery does. But, it works well when defining your own namespaces.

The outer function ensures the inner statements will be executed with jQuery as the definition of $. This will help out if you ever need to reuse your code in “no conflict” mode (http://api.jquery.com/jQuery.noConflict/).

Then, inside of the function, first check that the root namespace is defined under “window”, the global namespace. It took me longer than I would have liked to understand that “window” was the global namespace; I was under the sad impression that “document” was the global namespace.

Once the namespace you are looking to work with is created, then the $.extend() function gives the means to create the functionality you want.

You can then interact with your namespace the same way google of yahoo call their namespaced code:

alert(baseNamespace.subNamespace.someVariable); // 10
baseNamespace.subNamespace.someFunction(); // Also, 10

I hope this saves you a little bit of time when developing reusable javascript.

2 comments:

David Wright said...

Thanks, this has been a TODO of mine, "clean up javascript, define my own global namespace", this saved me some time.

jQuery is a great tool but lends itself to 'scattered' snippets interspersed through the code

Anonymous said...

This is a good tip. Thank you very much.

Post a Comment


Creative Commons License
This site uses Alex Gorbatchev's SyntaxHighlighter, and hosted by herdingcode.com's Jon Galloway.