Skip to content

Instantly share code, notes, and snippets.

@fidel-karsto
Last active December 20, 2015 11:59
Show Gist options
  • Save fidel-karsto/6127090 to your computer and use it in GitHub Desktop.
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.
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);
};
@fidel-karsto
Copy link
Author

usage:

namespace("package.string.seperated.with.dots", [context])

example

namespace("com.name.project.package.module")

Will produce the following namespace in the global object (window):

{
  "com": {
    "name": {
      "project": {
        "package": {
          "module": {}
         }
       }
     }
   }
}

You can pass in a context object as well (if the namespace shall be created in a different space than window):

var myContextObject = {};
namespace("com.name.project.package.module", myContextObject);

The reference to the most inner namespace object (package) is returned, which lets you use it like this:

namespace("package.component.model.property") = "foo";

Which will result in

{
  "package": {
    "component": {
      "model": {
        "property": "foo"
       }
     }
   }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment