Skip to main content

Custom Events

export class CustomEventManager<T = any> extends EventTarget {
private listener?: EventListenerOrEventListenerObject;
constructor(private name: string) {
super();
}

onTriggered(callback: (event: Event & { detail: T }) => void) {
this.listener = (e) => {
callback(e as Event & { detail: T });
};
this.addEventListener(this.name, this.listener);
}

removeListener() {
if (this.listener) this.removeEventListener(this.name, this.listener);
}

dispatch(data: T, eventInitDict?: CustomEventInit<T>) {
this.dispatchEvent(
new CustomEvent(this.name, { ...eventInitDict, detail: data })
);
}
}

export class CustomEventElementClass<T> {
private listener?: EventListener;
constructor(
private event: CustomEvent<T>,
private element: HTMLElement | Window = window
) {}

listen(cb: (e: CustomEvent<T>) => void) {
this.listener = cb as EventListener;
this.element.addEventListener(this.event.type, cb as EventListener);
}

dispatch() {
this.element.dispatchEvent(this.event);
}

removeListener() {
if (this.listener) {
this.element.removeEventListener(this.event.type, this.listener);
}
}
}
  • CustomEventElementClass : A class for creating a special EventTarget scoped to a class, and not to any element. This makes it more of a pattern and less based on the DOM.
  • CustomEventElementManager : A class for creating custom events on elements and dispatching them.