Skip to content

Instantly share code, notes, and snippets.

@davidmfoley
Created April 16, 2011 18:12
Show Gist options
  • Save davidmfoley/923364 to your computer and use it in GitHub Desktop.
Save davidmfoley/923364 to your computer and use it in GitHub Desktop.
Example javascript namespace declaration helper
// Replace App with your root namespace name.
//
// use like:
// App.declare('foo.bar.baz', function(){});
// App.foo.bar.baz();
// or
// App.declare('some.namespaceName', {foo : function(){}, bar:function(){}});
// App.some.namespaceName.foo();
var App = {};
(function() {
App.declare = function(ns, obj) {
if (typeof obj != 'function')
return $.extend(createNamespace(splitNamespace(ns)), obj);
return declareFunctionInNamespace(ns, obj);
};
function splitNamespace(ns) {
return ns.split('.');
}
function declareFunctionInNamespace(ns, obj) {
var namePieces = splitNamespace(ns);
var lastPiece = namePieces.pop();
var parent = createNamespace(namePieces);
if (parent[lastPiece])
$.extend(obj, parent[lastPiece]);
var toMix = {};
toMix[lastPiece] = obj;
return $.extend(parent, toMix)[lastPiece];
}
function createNamespace(namePieces) {
var obj = App;
$.each(namePieces, function (i, name) {
if (!obj[name]) {
obj[name] = {};
}
obj = obj[name];
});
return obj;
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment