Created
November 5, 2012 03:13
-
-
Save lukesutton/4015128 to your computer and use it in GitHub Desktop.
Simple function for declaring modules.
This file contains hidden or 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
| 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