jQuery: using namespaces

Sometimes you have to use more than one JavaScript framework. In this case, it's likely that some problems may arise especially when two libraries share the same syntax constructs. For example, both the Prototype and jQuery frameworks use $ as their preferred alias. Though most developers use the jQuery.noConflict() pattern to avoid such conflicts, sometimes it's preferable to wrap the jQuery object with a proper namespace. For example, you can use the namespace created by your own objects and wrap the jQuery object as a property of such objects. Example:

var App = {

   j: jQuery

}

By doing so, the jQuery wrapper is now part of the namespace created by your own application. Later you can use it this way:

App.j(document).ready(function() {
 
 alert('Test');
 
});

By doing so, you avoid any possible conflict. One major drawback of this approach is that you have to access your newly created property every time you want to use a jQuery expression. However, this prevents you from polluting the global namespace using a global variable.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.