Created
April 16, 2011 18:12
-
-
Save davidmfoley/923364 to your computer and use it in GitHub Desktop.
Example javascript namespace declaration helper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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