Created
August 7, 2014 07:02
-
-
Save julienrf/06bfb0d331ed126b60c4 to your computer and use it in GitHub Desktop.
Dependency injection in JavaScript
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
/* A basic implementation of bar */ | |
define(function () { | |
return { | |
plop: function () { alert('bar implementation'); } | |
} | |
}); |
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
/* An alternative implementation of bar */ | |
define(function () { | |
return { | |
plop: function () { alert('baz implementation'); } | |
} | |
}); |
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
/* | |
* foo is a module that depends on a bar module. | |
* Note that the dependency is modeled as a parameter of the function returned by the module definition. | |
*/ | |
define(function () { | |
return function (bar) { | |
return bar.plop() | |
} | |
}); |
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
/* The end-user wires dependencies */ | |
require(['foo', 'baz'], function (fooProvider, bazProvider) { | |
var baz = bazProvider(); | |
var foo = fooProvider(baz); | |
}) |
Ok, indeed if several implementations have a different API the problem is not the same :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It works because both
bar.js
andbaz.js
have the same API. It's like having interfaces and implementations. And in this case, you are right, it works fine.But in my case, for Prolyfill, the fact is that implementations were created before the interface (aka the spec) and so they all have more or less different APIs. You need a way to normalize that if you want to use any of them.
Also, it's not only about dependency but also about polyfill: if the global context already has the feature, do nothing, otherwise, create an implementation. You can only do that at runtime.