Created
April 16, 2015 02:44
-
-
Save Rafe/33cf0fb9728d0753ac39 to your computer and use it in GitHub Desktop.
Demonstrate how Angular.js injector works.
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
var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m; | |
var FN_ARG_SPLIT = /,/; | |
var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/; | |
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; | |
function annotate(fn) { | |
var $inject = [], | |
fnText, | |
argText, | |
last; | |
fnText = fn.toString().replace(STRIP_COMMENTS, ''); | |
argText = fnText.match(FN_ARGS)[1]; | |
argText.split(FN_ARG_SPLIT).forEach(function(arg) { | |
arg.replace(FN_ARG, function(all, underscore, name) { | |
$inject.push(name); | |
}); | |
}); | |
return $inject; | |
} | |
function createInjector(providers) { | |
return function injector(fn, self) { | |
var args = [], | |
$inject = annotate(fn); | |
$inject.forEach(function(arg) { | |
args.push(providers[arg]); | |
}); | |
return fn.apply(self, args); | |
} | |
} | |
var injector = createInjector({ | |
serviceA: 'hello', | |
serviceB: 'world', | |
}); | |
injector(function(serviceA, serviceB) { | |
console.log(serviceA, serviceB); // hello world | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment