@varaprasadh approach helped me get started, but lacked accumulating multiple events. Modified to also allow remove listener that functions similar to on DOM events to get rid of one based on callback.
class Dog {
constructor() {
this.listeners = {};
}
emit(method, payload = null) {
if (this.listeners.hasOwnProperty(method)) {
const callbacks = this.listeners[method];
for (let [key, callback] of Object.entries(callbacks)) {
if (typeof callback === 'function') {
callback(payload);
}
}
}
}
addEventListener(method, callback) {
if (!this.listeners.hasOwnProperty(method)) {
this.listeners[method] = {}
}
this.listeners[method][callback] = callback;
}
removeEventListener(method, callback) {
if (this.listeners.hasOwnProperty(method)) {
delete this.listeners[method][callback];
}
}
}