Last active
August 29, 2015 14:07
-
-
Save danprince/1fa687f382041b82ee4a to your computer and use it in GitHub Desktop.
Module System and Angular Style Dependency Injection 63 lines of Javascript.
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
(function(window) { | |
// global module list | |
var modules = {}; | |
// require a module | |
window.require = function(name) { | |
return modules[name]; | |
}; | |
// create a module getter on window | |
window.__defineSetter__('module', function(module) { | |
var deps = []; | |
// Check that a named function has been passed | |
if(!module.name) { | |
throw new Error('Modules need names!'); | |
} | |
// Make sure it's not overriding a current module | |
if(module.name in modules) { | |
throw new Error('Module already exists'); | |
} else { | |
// check dependencies | |
deps = getArgNames(module); | |
// store the result of calling the module | |
// with its dependencies injected | |
// + give it a new context for 'this' | |
// passing lambda to be later resolved, | |
// in order to avoid cyclic dependency | |
// errors. | |
modules[module.name] = module.apply({}, deps.map(resolve)); | |
} | |
}); | |
// turn a name into a module | |
function resolve(name) { | |
if(name in modules) { | |
return modules[name]; | |
} else { | |
throw new Error('Could not resolve dependency: ' + name); | |
} | |
} | |
// returns itself for filter functions | |
function identity(value) { | |
return value; | |
} | |
// returns an array of argument names | |
function getArgNames(fn) { | |
var str, exp; | |
str = fn.toString(); | |
exp = /\(([a-zA-Z0-9_$, ]*)\)/; | |
return exp.exec(str)[1] | |
.replace(' ', '') | |
.split(',') | |
.filter(identity); | |
} | |
})(window || global); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment