Last active
December 18, 2015 10:39
-
-
Save corymartin/5770583 to your computer and use it in GitHub Desktop.
Creates a namespace based upon a string representation of a namespace.
Adapted from a similar function in JavaScript Patterns by Stoyan Stefanov.
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
/* | |
* Creates a namespace based upon a string representation of a namespace. | |
* Adapted from a similar function in JavaScript Patterns by Stoyan Stefanov. | |
* | |
* @param {String} ns String representation of namespace. Eg, 'foo.bar.baz.goo' | |
* @returns {Object} Last object created in the namespace. | |
*/ | |
void function() { | |
var root = 'myapp'; | |
window[root] = window[root] || {}; | |
function namespace(ns) { | |
var parts = ns.split('.'); | |
if (parts[0] === root) { | |
parts = parts.slice(1); | |
} | |
var parent = window[root]; | |
for (var i = 0; i < parts.length; i++) { | |
if (parent[parts[i]] == null) { | |
parent[parts[i]] = {}; | |
} | |
parent = parent[parts[i]]; | |
} | |
return parent; | |
}; | |
namespace('util').namespace = namespace; | |
}(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment