Last active
November 17, 2018 22:50
-
-
Save bcomnes/8155cc64406bf6c81915c7d06916df89 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// https://medium.com/@WebReflection/dom-handleevent-a-cross-platform-standard-since-year-2000-5bf17287fd38 | |
export default class DOMEventHandler { | |
constructor(ctx, node) { | |
if (!ctx) throw new Error("DOMEventHandler: A context is required."); | |
this.ctx = ctx; | |
if (node) this.addEventListeners(node); | |
} | |
get events() { | |
return ( | |
this._events || | |
Object.defineProperty(this, "_events", { | |
value: Object.getOwnPropertyNames(this.ctx.constructor.prototype) | |
.filter(type => /^on/.test(type)) | |
.map(type => type.slice(2)) | |
})._events | |
); | |
} | |
handleEvent(event) { | |
this.ctx["on" + event.type](event); | |
} | |
addEventListeners(node) { | |
for ( | |
let events = this.events, i = events.length; | |
i--; | |
node.addEventListener(events[i], this) | |
); | |
} | |
removeEventListeners(node) { | |
for ( | |
let events = this.events, i = events.length; | |
i--; | |
node.removeEventListener(events[i], this) | |
); | |
} | |
} |
This file contains hidden or 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
// Example use of CTX event handler | |
import DOMEventHandler from "ctx-dom-event-handler" | |
class MyWSController extends SomeOtherClass { | |
constructor () { | |
this.ws = new WebSocket('ws://localhost:8080'); | |
this.handler = new DOMEventHandler(this, this.ws) | |
} | |
onmessage (ev) {} | |
onopen (ev) {} | |
onerror (ev) {} | |
onclose (ev) {} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This turned out to be a useful pattern. I made it a module https://github.com/bcomnes/dom-event-handler