Skip to content

Instantly share code, notes, and snippets.

@julienrf
Created August 7, 2014 07:02
Show Gist options
  • Save julienrf/06bfb0d331ed126b60c4 to your computer and use it in GitHub Desktop.
Save julienrf/06bfb0d331ed126b60c4 to your computer and use it in GitHub Desktop.
Dependency injection in JavaScript
/* A basic implementation of bar */
define(function () {
return {
plop: function () { alert('bar implementation'); }
}
});
/* An alternative implementation of bar */
define(function () {
return {
plop: function () { alert('baz implementation'); }
}
});
/*
* 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()
}
});
/* The end-user wires dependencies */
require(['foo', 'baz'], function (fooProvider, bazProvider) {
var baz = bazProvider();
var foo = fooProvider(baz);
})
@julienrf
Copy link
Author

julienrf commented Aug 7, 2014

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