Skip to content

Instantly share code, notes, and snippets.

@maxgfr
Last active April 10, 2024 13:37
Show Gist options
  • Save maxgfr/fd8278a4d8adf33b8b962250e51e08cc to your computer and use it in GitHub Desktop.
Save maxgfr/fd8278a4d8adf33b8b962250e51e08cc to your computer and use it in GitHub Desktop.
Example of an emitter using observer pattern
export enum EventType {
SEND_RESULT_EVENT = "sendResultEvent",
SEND_RANDOM_ITEM = "sendRandomItem",
}
export type CallbackEventType = {
[EventType.SEND_RESULT_EVENT]: (isEligible: boolean) => void;
[EventType.SEND_RANDOM_ITEM]: (valueA: string, valueB: number) => void;
};
export const eventEmitter: {
readonly events: Record<string, CallbackEventType[EventType][]>;
dispatch<T extends EventType>(
eventType: T,
...values: Parameters<CallbackEventType[T]>
): void;
subscribe<T extends EventType>(
eventType: T,
callback: CallbackEventType[T]
): void;
unsubscribe<T extends EventType>(eventType: T): void;
} = {
events: {},
dispatch<T extends EventType>(
event: T,
...values: Parameters<CallbackEventType[T]>
) {
if (!this.events[event]) return;
this.events[event].forEach((callback: any) =>
callback(...(values as Parameters<CallbackEventType[T]>))
);
},
subscribe(event, callback) {
if (!this.events[event]) this.events[event] = [];
if (!this.events[event]?.includes(this.events[event][0]))
this.events[event]?.push(callback);
},
unsubscribe(event) {
if (!this.events[event]) return;
delete this.events[event];
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment