Welcome, guest | Sign In | My Account | Store | Cart

This recipe enables you to modularize javascript libraries by placing all library code within a namespace object. All namespaces are rooted at "window.global_namespace". References between namespaces are supported by the Import function, which allows forward references to namespaces that have yet to be defined.

See code comment for more detailed examples.

JavaScript, 164 lines
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
/* Namespace.js

   Version 1.0, June 2009
   by Mike Koss - released into the public domain.

   Support for building modular namespaces in javascript.
   
   Globals:
   
   window.global_namespace (Namespace) - The top of the namespace heirarchy.  Child namespaces
   are stored as properties in each namespace object.
   
   *** Class Namespace ***

   Methods:

   ns.Define(sPath, fnCallback(ns)) - Define a new Namespace object and call
   the provided function with the new namespace as a parameter.
   
   	sPath - Path of the form ('unique.module.sub_module').
   
   Returns the newly defined namespace.
   
   ns.Extend(oDest, oSource) - Copy the (own) properties of the source object
   into the destination object.  Returns oDest.  Note: This method is a convenience
   function - it has no effect on the Namespace object itself.
   
   ns.Import(sPath) - Return the namespace object with the given (absolute) path.
   
   Usage example:
   
   global_namespace.Define('startpad.base', function(ns) {
       var Other = ns.Import('startpad.other');

       ns.Extend(ns, {
           var1: value1,
           var2: value2,
           MyFunc: function(args)
               {
               ....Other.AFunction(args)...
               }
       });
       
       ns.ClassName = function(args)
       {
       };
       
       ns.ClassName.prototype = {
           constructor: ns.ClassName,
           var1: value1,
           
       Method1: function(args)
           {
           }
       };
   });
*/

// Define stubs for FireBug objects if not present
// This is here because this will often be the very first javascript file loaded
if (!window.console)
	{
	(function ()
		{
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
    "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];

    window.console = {};
    for (var i = 0; i < names.length; ++i)
    	{
        window.console[names[i]] = function() {};
        }
		})();
	}

(function()
{
	var sGlobal = 'global_namespace';

	// Don't run this function more than once.
	if (window[sGlobal])
		return;
	
	var ns = window[sGlobal] = new Namespace(null); 

	function Namespace(nsParent, sName)
		{
		if (sName)
			sName = sName.replace(/-/g, '_');

		this._nsParent = nsParent;
		
		if (this._nsParent)
			{
			this._nsParent[sName] = this;
			this._sPath = this._nsParent._sPath;
			if (this._sPath != '')
				this._sPath += '.';
			this._sPath += sName;
			}
		else
			this._sPath = '';
		};
	
	Namespace.prototype.Extend = function(oDest)
		{
		for (var i = 1; i < arguments.length; i++)
			{
			var oSource = arguments[i];
			for (var prop in oSource)
				{
				if (oSource.hasOwnProperty(prop))
					oDest[prop] = oSource[prop];
				}
			}
	
		return oDest;
		};
		
	ns.Extend(Namespace.prototype, {
	Define: function (sPath, fnCallback)
		{
		sPath = sPath.replace(/-/g, '_');

		var aPath = sPath.split('.');
		var nsCur = this;
		for (var i = 0; i < aPath.length; i++)
			{
			var sName = aPath[i];
			if (nsCur[sName] == undefined)
				new Namespace(nsCur, sName);
			nsCur = nsCur[sName];
			}
		// In case a namespace is multiply loaded - we ignore the definition function
		// for all but the first call.
		if (fnCallback)
			{
			if (!nsCur._fDefined)
				{
				nsCur._fDefined = true;
				fnCallback(nsCur);
				console.info("Namespace '" + nsCur._sPath + "' defined.");
				}
			else
				console.warn("WARNING: Namespace '" + nsCur._sPath + "' redefinition.");
			}
		else if (!nsCur._fDefined)
			console.warn("Namespace '" + nsCur._sPath + "' forward reference.");
		return nsCur;
		},
	
	Import: function(sPath)
		{
		return window.global_namespace.Define(sPath);
		},
		
	SGlobalName: function(sInNamespace)
		{
		sInNamespace = sInNamespace.replace(/-/g, '_');
		return sGlobal + '.' + this._sPath + '.' + sInNamespace;
		},
	});

})();
Created by Mike Koss on Sun, 12 Jul 2009 (MIT)
JavaScript recipes (69)
Mike Koss's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks