Skip to content

Instantly share code, notes, and snippets.

@andyrichardson
Last active February 12, 2021 11:56
Show Gist options
  • Save andyrichardson/a928ad0f80e949369707fb986ff84f41 to your computer and use it in GitHub Desktop.
Save andyrichardson/a928ad0f80e949369707fb986ff84f41 to your computer and use it in GitHub Desktop.

About

A type safe event target implementation.

Creation

type Events = 
  | Event<'start', StartType>
  | Event<'stop', StartType>;
  
const target = new EventTarget<Events>();

Add event listener

target.addEventListener('start', startHandler);

Remove event listener

target.removeEventListener('start', startHandler);

Dispatch event

Note: A slight deviation from the JS standard EventTarget

target.dispatchEvent('start', payload);
export type Event<K extends string = string, V extends any = any> = {
key: K;
value: V;
};
export class EventTarget<T extends Event> {
private listeners: { [key in T["key"]]?: Array<(event: any) => void> } = {};
public addEventListener<K extends T["key"]>(
type: K,
handler: (event: EventValue<T, K>) => void
) {
this.listeners[type] = [...(this.listeners[type] || []), handler];
}
public removeEventListener<K extends T["key"]>(
type: K,
handler: (event: EventValue<T, K>) => void
) {
if (!this.listeners[type]) {
return;
}
this.listeners[type] = this.listeners[type].filter((l) => l !== handler);
};
public dispatchEvent<K extends T["key"]>(type: K, event: EventValue<T, K>) {
this.listeners[type].forEach((handler) => handler(event));
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment