Last active
September 27, 2015 13:17
-
-
Save domenic/1276149 to your computer and use it in GitHub Desktop.
Intermediate DI/service locator solution for JavaScript modules
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
////////////////////////// | |
// 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(); | |
} | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@bolshchikov thanks, fixed