Skip to content

Instantly share code, notes, and snippets.

@JamesMGreene
Created July 8, 2012 12:14
Show Gist options
  • Save JamesMGreene/3070677 to your computer and use it in GitHub Desktop.
Save JamesMGreene/3070677 to your computer and use it in GitHub Desktop.
Shortcut functions to easily create deep namespaces in JavaScript
(function(exports) {
/**
* @namespace My namespace!
*/
exports.MyNS = {
/**
* Returns the namespace object specified and creates it if it doesn't exist.
* Does NOT enforce that any requested namespace is attached to the MyNS root namespace.
*
* @param {String} nsString A string representation of the desired namespace.
* @return {Object} A reference to the namespace object.
*
* @example
* MyNS.CreateNamespace("MyNS.Doc.Feature"); // Returns MyNS.Doc.Feature
* MyNS.Doc.Feature.Widget = function() {};
*
* @example
* MyNS.CreateNamespace("Doc.Feature"); // Returns Doc.Feature (MyNS root namespace is NOT enforced!)
* Doc.Feature.Widget = function() {};
*/
CreateNamespace: function(nsString) {
var ns;
if (nsString) {
ns = nsString.split(".").reduce(function(pv, cv) { return pv[cv] = pv[cv] || {}; }, exports);
}
return ns;
}
}
})(this);
(function(exports) {
var myNsString = "MyNS";
/**
* @namespace My namespace!
*/
exports[myNsString] = {
/**
* Returns the namespace object specified and creates it if it doesn't exist.
* Enforces that any requested namespace is attached to the MyNS root namespace.
*
* @param {String} nsString A string representation of the desired namespace.
* @return {Object} A reference to the namespace object.
*
* @example
* MyNS.CreateNamespace("MyNS.Doc.Feature"); // Returns MyNS.Doc.Feature
* MyNS.Doc.Feature.Widget = function() {};
*
* @example
* MyNS.CreateNamespace("Doc.Feature"); // Also returns MyNS.Doc.Feature (MyNS root namespace is enforced)
* MyNS.Doc.Feature.Widget = function() {};
*/
CreateNamespace: function(nsString) {
var ns;
if (nsString) {
ns = nsString.split(".").reduce(function(pv, cv, i) {
// Ignore the first item if it matches your enforced root namespace
if (i === 0 && cv === myNsString) {
return pv;
}
return pv[cv] = pv[cv] || {};
}, exports[myNsString]);
}
return ns;
}
}
})(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment