Joe Honton
Jun 3, 2022

--

Even more powerful: you can use EventTarget as a base class on objects that are completely separate from the DOM.

class Signal extends EventTarget {

broadcast(topic, data) {

const customEvent = new CustomEvent(topic, {detail: data});

this.dispatchEvent(customEvent);

}

listen(topic, callback) {

this.addEventListener(topic, (event) => {

callback(event.detail);

});

}

}

In this way I can use Signal's broadcast and listen methods as a complete publish/subscribe message broker.

--

--

Joe Honton
Joe Honton

Written by Joe Honton

Princeps geographus, Read Write Tools

No responses yet