Skip to content

Instantly share code, notes, and snippets.

@erithmetic
Created April 15, 2011 14:22
Show Gist options
  • Save erithmetic/921779 to your computer and use it in GitHub Desktop.
Save erithmetic/921779 to your computer and use it in GitHub Desktop.
OOP Events
// Here's the code I'm working with now:
Careplane = function() {};
Careplane.prototype.onPageLoad = function(ev) {
if(this.firstRun)
this.firstRun();
this.doc = ev.originalTarget;
this.chooseAndLoadDriver();
};
// Firefox extension loading code
Overlay = {
onLoad: function() {
var node = document.getElementById('somenode');
if(node) {
var extension = new Careplane();
node.addEventListener("DOMContentLoaded", Util.proxy(extension.onPageLoad, extension), true);
}
}
}
// Contrast with
Careplane = function() {};
Careplane.prototype.welcome = function() { ... };
Careplane.prototype.chooseAndLoadDriver = function(doc) { ... };
ExtensionLoader = {
onPageLoad: function(extension) {
return function(ev) {
extension.welcome();
extension.chooseAndLoadDriver(ev.originalTarget);
};
}
}
// Firefox extension loading code
Overlay = {
onLoad: function() {
var node = document.getElementById('somenode');
if(node) {
var extension = new Careplane();
node.addEventListener("DOMContentLoaded", ExtensionLoader.onPageLoad(extension), true);
}
}
}
// I think this more clearly defines an interface between Firefox's loading code and Careplane.
// The handler defined in ExtensionLoader uses a "tell, don't ask" policy (http://pragprog.com/articles/tell-dont-ask).
// It seems simpler overall and easier to read.
// It's a more functional approach using closures.
// It delegates the job of handling events into a separate class.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment