Skip to content

Instantly share code, notes, and snippets.

@lili21
Created September 1, 2015 05:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lili21/7c333f6b311724d5d245 to your computer and use it in GitHub Desktop.
Save lili21/7c333f6b311724d5d245 to your computer and use it in GitHub Desktop.
dependency injection
var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
var FN_ARG_SPLIT = /, ?/g;
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
var injector = {
store: {},
register: function(key, value) {
this.store[key] = value;
},
invoke: function(fn) {
var self = this;
var $inject = [];
if (fn.length) {
fnText = fn.toString().replace(STRIP_COMMENTS, '');
argDecl = fnText.match(FN_ARGS)[1];
args = argDecl.split(FN_ARG_SPLIT);
$inject = args.map(function(arg) {
return self.store[arg];
});
fn.apply(undefined, $inject);
}
}
};
injector.register('add', function(a, b) {
return a + b;
});
injector.invoke(function(add) {
console.log(add(3, 4));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment