Created
July 21, 2014 19:08
-
-
Save domenic/722cdac2f9f79f71ad0c to your computer and use it in GitHub Desktop.
Trying and failing to emulate EventTarget error handling with JS
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
function EventEmitter() { | |
this._eventsMap = Object.create(null); | |
} | |
EventEmitter.prototype.on = function (eventName, handler) { | |
if (!this._eventsMap[eventName]) { | |
this._eventsMap[eventName] = []; | |
} | |
this._eventsMap[eventName].push(handler); | |
}; | |
EventEmitter.prototype.off = function (eventName, handler) { | |
var handlers = this._eventsMap[eventName]; | |
if (!handlers) { | |
return; | |
} | |
var index = handlers.indexOf(handler); | |
if (index === -1) { | |
return; | |
} | |
handlers.splice(index, -1); | |
}; | |
EventEmitter.prototype.emit = function (eventName) { | |
var handlers = this._eventsMap[eventName]; | |
if (!handlers) { | |
return; | |
} | |
var args = Array.prototype.slice.call(arguments, 1); | |
executeHandler(0); | |
function executeHandler(index) { | |
if (index >= handlers.length) { | |
return; | |
} | |
try { | |
handlers[index].apply(undefined, args); | |
} finally { | |
executeHandler(index + 1); | |
} | |
} | |
}; | |
var ee = new EventEmitter(); | |
ee.on("foo", function (x) { | |
console.log("my EE handler #1: ", x); | |
}); | |
ee.on("foo", function (x) { | |
console.log("my EE handler #2: ", x); | |
throw new Error("boo!"); | |
console.log("should never get here"); | |
}); | |
ee.on("foo", function (x) { | |
console.log("my EE handler #3: ", x); | |
}); | |
ee.emit("foo", "arg"); | |
// result: my EE handler #1, my EE handler #2, my EE handler #3, boo! | |
//// | |
window.addEventListener("foo", function (x) { | |
console.log("EventTarget handler #1: ", x); | |
}); | |
window.addEventListener("foo", function (x) { | |
console.log("EventTarget handler #2: ", x); | |
throw new Error("boo!"); | |
console.log("should never get here"); | |
}); | |
window.addEventListener("foo", function (x) { | |
console.log("EventTarget handler #3: ", x); | |
}); | |
window.dispatchEvent(new CustomEvent("foo", { detail: "arg" })); | |
// result: EventTarget handler #1, EventTarget handler #2, boo!, EventTarget handler #3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment