Skip to content

Instantly share code, notes, and snippets.

@domenic
Last active September 27, 2015 13:17
Show Gist options
  • Save domenic/1276149 to your computer and use it in GitHub Desktop.
Save domenic/1276149 to your computer and use it in GitHub Desktop.
Intermediate DI/service locator solution for JavaScript modules
//////////////////////////
// Pure "DI style" modules
// BackEndAnalytics.js
define(function () {
return function BackEndAnalytics() {
this.send = function () { };
};
});
// FrontEndAnalytics.js
define(function () {
return function FrontEndAnalytics() {
this.send = function () { };
this.sendScreenInfo = function (colorDepth, width, height) { };
};
});
// Analytics.js
define(function () {
return function Analytics(backEndAnalytics, frontEndAnalytics, screen) {
this.send = function () {
backendAnalytics.send();
frontEndAnalytics.send();
frontEndAnalytics.sendScreenInfo(screen.colorDepth, screen.width, screen.height);
};
};
});
// NullAnalytics.js
define(function () {
// Null object pattern
return function NullAnalytics() {
this.send = function () { };
}
});
/////////////////////////
// Service-located singleton modules that lots of legacy code depends on.
// In a pure DI system, these would not exist; e.g. the legacy code would get an Analytics instance injected into it,
// and the code that is inside of these module would get moved up to the composition root.
// configuration.js
define(function () {
return {
isInProduction: true
};
});
// analytics.js
define(["BackEndAnalytics", "FrontEndAnalytics", "Analytics", "NullAnalytics", "configuration"],
function (BackEndAnalytics, FrontEndAnalytics, Analytics, NullAnalytics, configuration) {
var analytics = configuration.isInProduction
? new Analytics(new BackEndAnalytics(), new FrontEndAnalytics(), window.screen)
: new NullAnalytics();
return {
send: analytics.send
};
});
//////////////////////
// Client legacy code
// frobber.js
define(["analytics"], function (analytics) {
return {
frob: function () {
console.log("frobbing");
analytics.send();
}
};
});
@bolshchikov
Copy link

line 13: should it be FrontEndAnalytics instead of BackEndAnalytics?

@domenic
Copy link
Author

domenic commented Jun 19, 2013

@bolshchikov thanks, fixed

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