Skip to content

Instantly share code, notes, and snippets.

@lukesutton
Created November 5, 2012 03:13
Show Gist options
  • Select an option

  • Save lukesutton/4015128 to your computer and use it in GitHub Desktop.

Select an option

Save lukesutton/4015128 to your computer and use it in GitHub Desktop.
Simple function for declaring modules.
function module(scope, fn) {
var result = fn();
if (_.isEmpty(result)) {
throw "When defining a module, you _must_ return an object containing exports.";
}
var split = scope.split('.');
if (split.length > 1) {
var parts = _.initial(split, 1),
last = _.last(split),
target = window;
for (var i = parts.length - 1; i >= 0; i--) {
var part = parts[i];
if (_.isUndefined(target[part])) {
target[part] = {};
}
else if (!_.isObject(target[part])) {
throw "You can't define a module against a scope that's not an object.";
}
target = target[part];
};
target[last] = result;
}
else {
window[split[0]] = result;
}
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment