Created
October 1, 2013 14:44
-
-
Save nkijak/6779617 to your computer and use it in GitHub Desktop.
Dependency Injection a la angular with "$" variables denoting wired values
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 regex(func) {return new RegExp(func.name+"\\(([$?\\w+, ?]*)\\)");} | |
function meta(func) { | |
var matches = regex(func).exec(func.toString().replace(" ", "")); | |
var args = matches[1].split(","); | |
return {name: func.name, args: args.map(function(arg){ return arg.replace(" ", ""); })}; | |
} | |
function wrapper(func, factory) { | |
var args = meta(func).args; | |
var injectedArgs = args.map(function(arg) { | |
var injection = factory[arg.replace("$", "")]; | |
return injection || arg; | |
}); | |
return function () { | |
var i = 0; | |
var outsideArgs = arguments; | |
var functionArguments = args.map(function(arg) { | |
var injection = factory[arg.replace("$", "")]; | |
console.log("replacing %s with ", arg, injection); | |
return injection || outsideArgs[i++]; | |
}); | |
console.log(functionArguments); | |
console.log("new function takes %d arguments", i); | |
func.apply(func, functionArguments); | |
} | |
} | |
function a($inj, name, $value) { | |
console.log($inj,name,$value); | |
} | |
var aPrimed = wrapper(a,{"inj":"INJECTED", "value":"VALUE"}); | |
aPrimed("name"); | |
console.log(aPrimed.toString()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment