Last active
December 20, 2015 11:59
-
-
Save fidel-karsto/6127090 to your computer and use it in GitHub Desktop.
Convenient function to create namespaces by passing in a string and a scope object.
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
var namespace = function namespace (packagesStr, context) { | |
var myContext = context || window, | |
packages = (packagesStr && typeof packagesStr === "string") ? packagesStr.split(".") : [], | |
create = function create (pkg, folders) { | |
if (pkg && typeof this[pkg] === "undefined") { | |
this[pkg] = {}; | |
} | |
if (folders && folders.length > 0) { | |
return create.call(this[pkg], folders.shift(), folders); | |
} | |
}; | |
return create.call(myContext, packages.shift(), packages); | |
}, | |
checkNamespace = function (packagesStr, context) { | |
var myContext = context || window, | |
packages = (packagesStr && typeof packagesStr === "string") ? packagesStr.split(".") : [], | |
exists = true, | |
check = function check (pkg, folders) { | |
if (pkg && typeof this[pkg] === 'undefined') { | |
return false; | |
} | |
if (folders && folders.length > 0) { | |
return exists && check.call(this[pkg], folders.shift(), folders); | |
} | |
return (typeof this[pkg] !== 'undefined'); | |
}; | |
return check.call(myContext, packages.shift(), packages); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
usage:
example
Will produce the following namespace in the global object (window):
You can pass in a context object as well (if the namespace shall be created in a different space than window):
The reference to the most inner namespace object (package) is returned, which lets you use it like this:
Which will result in