Tag Archives: javascript

Javascript Namespaces

One of the big problems as the number of toolkits that you can use in your RIA increases is variable collision.  Constructing your classes and widgets in the form of a namespace reduces the risk that the global variables you are using will have been used by someone else.  The following code demonstrates a pattern for defining a namespace utilizing objects to create an object hierarchy for your namespace.

var MyNamespace = {};
 MyNamespace.test = function(){
         alert("MyNamespace.test");
 };

 MyNamespace.common = {};
 MyNamespace.common.test = function(){
         alert("MyNamespace.common.test");
 };

 MyNamespace.utilities = {};
 MyNamespace.utilities.test = function(){
         alert("MyNamespace.utilities.test");
 };

 MyNamespace.common.dataaccess = {};
 MyNamespace.common.dataaccess.test = function(){
    alert("MyNamespace.common.dataaccess.test");
 };

Notice that before the namespace can be assigned variables and functions, it needs to be initialized to an empty object.

This allows you to make calls like:

MyNamespace.common.dataaccess.test();

However, it is important that you only initialize the name space object once, and it is important that the full path of namespace objects be declared before you try and assign functions and properties to them.

If you want to separate your name space implementation across separate files, then you really need to check that all the stages of the namespace are assigned and create them if not. e.g.

 if(!MyNamespace) MyNameSpace = {};
 if(!MyNamespace.common ) MyNameSpace.common = {};
 if(!MyNamespace.common.dataaccess) MyNameSpace.common.dataaccess = {};

You can imagine that if your namespaces get quite deep, you start having quite a lot of code at the start of each of your Javascript files just to ensure the namespace objects are created.  There is however a very nice solution in the Ext library which helps you with this:

Ext.namespace() – this takes a variable list of namespace names and creates the objects for you if they don’t exist.

e.g.

 Ext.namespace("MyNamespaces","MyNamespace.common","MyNamespace.common.dataaccess");

Creating a JavaScript Singleton object

If we want to create a singleton object, i.e. there can only every be one instance of it that is referenced by a global variable, in JavaScript it is very easy.  We simply declare the class function inline, returning a new object with the public methods and properties on, directly followed by () parenthesis and assign it to our global variable.

If you want to create private methods and functions then you should be able to see the similarities of this and the JavaScript Class Patterns article.

var MySingleton = function(){
    return {
        // variables and methods
         id : 1,

         test : function()
         {
             return this.id;
         }
     }
 }();