Created
March 4, 2011 16:16
-
-
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
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
/* | |
* 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