A generic DOM event handler implementing the EventListener interface for class methods. Works great in the browser. Does't work great in the Node.js ecosystem.
$ npm install dom-event-handler
const DOMEventHandler = require("dom-event-handler")
class MyWSController extends SomeOtherClass {
constructor () {
this.ws = new WebSocket('ws://localhost:8080')
this.handler = new DOMEventHandler(this, this.ws)
}
// These methods handle the websocket events
onmessage (ev) {}
onopen (ev) {}
onerror (ev) {}
onclose (ev) {}
}
Isn't that nicer than this?
const ws = new WebSocket('ws://localhost:8080')
class VerboseWSController {
constructor () {
this.foo = 'bar'
// You have to bind since you don't pass a full context.
// Static class properties assigned to arrow functions are less verbose
// but are structurally similar to binding, and have poor env support still.
// They don't reside on the prototype. That may or may not matter to the use case.
this.onmessage = this.onmessage.bind(this)
this.onopen = this.onopen.bind(this)s
this.onerror = this.onerror.bind(this)
this.onclose = this.onclose.bind(this)
}
onmessage (ev) {}
onopen (ev) {}
onerror (ev) {}
onclose (ev) {}
}
const c = new VerboseWSController()
ws.addEventListener('message', c.onmessage)
ws.addEventListener('open', c.onopen)
ws.addEventListener('error', c.onerror)
ws.addEventListener('close', c.onclose)
Create a new instance of DOMEventHandler
passing in a context ctx
(often this
when created within a class) and optionally a DOM event target node
(e.g. an event emitting DOM node) to attach listeners to on instantiation.
The ctx
should be an object who's prototype contains event handler methods. Event handler methods must take the form of on{eventname}
where eventname
is the name of the event you want to listen on and handle (the name you would pass to node.addEventListener
). In practice, you can pass a class instance as a ctx
, or this
when the instance owns the DOMEventHanlder
instance.
Attach all event
handler methods on ctx
to the DOM event target node
.
Remove all event
handler event names on ctx
from the DOM event target node
.
You don't need to call these, but they are there.
Implements the eventListener.handleEvent
method for the events
found on the ctx
prototype. This is where the magic happens.
A getter that returns all events found on the ctx
the handler is bound to. The events returned from this getter are what get attached and detached in the above methods.
This module was inspired by a @webreflection article.
This is a slick API, but has poor support in the Node.js ecosystem due to poor support for the EventListener interface (Node.js style events do not support handleEvent or similar). For a similar API see node-event-handler, which lacks the bind free benefits of this approach, but can provide a stand-in api when writing universal Node.js code.