Skip to content

Instantly share code, notes, and snippets.

@mbbx6spp
Created March 4, 2011 16:16
Show Gist options
  • Save mbbx6spp/854898 to your computer and use it in GitHub Desktop.
Save mbbx6spp/854898 to your computer and use it in GitHub Desktop.
Illustration of provider idiom in Javascript for sharing with fellow Code PaLOUsa 2011 conference attendee from this morning #CPL11
/*
* Javascript provider idiom illustrated
* @author Susan Potter
* @date 2011-01-28
*/
// FinEnv "interface"
var FinEnv = function () {
return {
println: function (output) {
// TODO: impelment for each env provider
},
print: function (output) {
// TODO: implement for each env provider
},
require: function (include) {
// TODO: implement for each env provider
}
}
}();
// included for browser environment
(function (envBase) {
envBase.println = function (output) {
document.write('<p>' + output + '</p>');
};
envBase.print = function (output) {
document.write('<br>' + output);
};
envBase.require = function (include) {
document.write('<script src="' + include + '"></script');
};
return envBase;
}) (FinEnv);
// included for Rhino environment
(function (envBase) {
envBase.println = function (output) {
print(output + '\n');
};
envBase.print = function (output) {
print(output);
};
envBase.require = function (include) {
require(include);
};
return envBase;
}) (FinEnv);
// included for NodeJS environment
(function (envBase) {
envBase.println = function (output) {
console.log(output + '\n');
};
envBase.print = function (output) {
require('util').print(output);
};
envBase.require = function (include) {
require(include);
};
return envBase;
}) (FinEnv);
// included for FreeSWITCH environment
(function (envBase) {
envBase.println = function (output) {
console_log(output + '\n');
};
envBase.print = functiion (output) {
console_log(output);
};
envBase.require = function (include) {
use(include);
};
}) (FinEnv);
// in application code can run in browser, Rhino or NodeJS now!
FinEnv.println("This blows my mind.");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment