Skip to content

Instantly share code, notes, and snippets.

@CarlMungazi
Created November 18, 2019 19:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CarlMungazi/5dcce4611a905b3ec23e12e29a35e920 to your computer and use it in GitHub Desktop.
Save CarlMungazi/5dcce4611a905b3ec23e12e29a35e920 to your computer and use it in GitHub Desktop.
// Here's an explanation of how this works:
// 1. The event names are always (by design) prefixed by `on`.
// 2. The EventListener interface accepts either a function or an object
// with a `handleEvent` method.
// 3. The object does not inherit from `Object.prototype`, to avoid
// any potential interference with that (e.g. setters).
// 4. The event name is remapped to the handler before calling it.
// 5. In function-based event handlers, `ev.target === this`. We replicate
// that below.
// 6. In function-based event handlers, `return false` prevents the default
// action and stops event propagation. We replicate that below.
function EventDict() {
// Save this, so the current redraw is correctly tracked.
this._ = currentRedraw
}
EventDict.prototype = Object.create(null)
EventDict.prototype.handleEvent = function (ev) {
var handler = this["on" + ev.type]
var result
if (typeof handler === "function") result = handler.call(ev.currentTarget, ev)
else if (typeof handler.handleEvent === "function") handler.handleEvent(ev)
if (this._ && ev.redraw !== false) (0, this._)()
if (result === false) {
ev.preventDefault()
ev.stopPropagation()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment