-
-
Save cjohansen/8689463 to your computer and use it in GitHub Desktop.
| // An innocent-looking function | |
| function getInjected(lol) { | |
| console.log(lol); | |
| } | |
| var di = initializeDI(); | |
| di.add("lol", 42); | |
| // A pretty weird function call | |
| di.invoke(getInjected); // "42" | |
| // Another innocent-looking function | |
| function doIt(answerToLifeTheUniverseAndEverything) { | |
| console.log(answerToLifeTheUniverseAndEverything); | |
| } | |
| // Decided to name function-local variables differently, eh? NO SOUP FOR YOU | |
| di.invoke(doIt); // "undefined" | |
| // A dependency injection "framework" | |
| function initializeDI() { | |
| function argNames(fn) { | |
| var args = fn.toString().match(/\((.*?)\)/)[1]; | |
| if (args.trim() === "") { return []; } | |
| return args.split(",").map(function (a) { return a.trim(); }); | |
| } | |
| var deps = {}; | |
| return { | |
| add: function (name, value) { deps[name] = value; }, | |
| invoke: function (fn, thisp) { | |
| return fn.apply(thisp, (fn.$inject || argNames(fn)).map(function (a) { | |
| return deps[a]; | |
| })); | |
| } | |
| }; | |
| } |
mindblowing ! http://bit.ly/1hN2ole
Right, that's all about it. Perhaps, it would be better to raise an error instead of an undefined. Since, if my dependency is missing, I want an exception.
There are some further things that could be done to it yet, just to realize in the end that dependency injection is really a poor man's "require".
Let me just clarify that I really don't think this is a good way to handle data flow or dependencies. This kind of code severely reduces my abilities to reason about the flow of data, and available data and/or modules.
This snippet illustrates complexity of the worst kind: it looks benign on the surface, but hides severe complexity. I would prefer a bunch of global variables to this. At least I can use Object.keys with global/window
ridiculous^2