jQuery Namespace Plug-in

When I am doing JavaScript development, I prefer to put all my code under specific namespaces. For instance, if I am doing a personal project, I’ll stick everything under a “core” space, and build additional spaces underneath such as “Comments”, “Utils”, etc. The problem with this approach is, every time a new namespace is being created, I have to check to make sure every space before it is already there. So I ended up writing a very simple jQuery plug-in that takes care of this task for me.

Basically, what I would like to do is give a namespace pattern to the plug-in and extend it in a single step. Before I share the code, let’s see how I actually use it:

$.extend($.namespace("core.Comments"), {

[variables, functions, etc.]

});

Here, $.namespace takes a namespace pattern as a string, parses it, and creates all required objects. If they are already there, it doesn’t touch them. Then we use jQuery’s beautiful $.extend method to add our code inside the last space.

Without further ado, here is the actual plug-in code:

(function($) {

$.extend({

namespace : function(spaces) {
var parent_space = window;
var namespaces = spaces.split(".");
 
for (var i = 0; i < namespaces.length; i++) {
if (typeof parent_space[namespaces[i]] == "undefined") {
parent_space[namespaces[i]] = new Object();
}
 
parent_space = parent_space[namespaces[i]];
}
 
return parent_space;
}

});

})(jQuery);

Extremely simple - we split the namespace pattern on dots, then iterate over the array, creating the space under the window object. Finally we return the latest space.

This is extremely useful in Django applications when I might insert some additional variables such as the MEDIA_URL into my JavaScript spaces. I can easily do this now in my template, without having to check whether the namespace is already created or not:

<script type="text/javascript">
//<![CDATA[
$.extend($.namespace("core"), {
media_url : "{{ MEDIA_URL }}"
});
//]]>
</script>

I hope this will be useful for other people. You can download the plug-in from its repository on GitHub.