Skip to content

Instantly share code, notes, and snippets.

@cjohansen
Last active August 29, 2015 13:55
Show Gist options
  • Save cjohansen/8689463 to your computer and use it in GitHub Desktop.
Save cjohansen/8689463 to your computer and use it in GitHub Desktop.
JavaScript "Dependency injection" in all its ridiculous glory.
// 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];
}));
}
};
}
@ku1ik
Copy link

ku1ik commented Jan 29, 2014

ridiculous^2

@jacobandresen
Copy link

mindblowing ! http://bit.ly/1hN2ole

@reebalazs
Copy link

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".

@cjohansen
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment