Skip to content

Instantly share code, notes, and snippets.

@Ari24-cb24
Last active March 31, 2024 16:40
Show Gist options
  • Save Ari24-cb24/fd642a207ef46aa7c463d81682a019a7 to your computer and use it in GitHub Desktop.
Save Ari24-cb24/fd642a207ef46aa7c463d81682a019a7 to your computer and use it in GitHub Desktop.
Simple, small eventhandler for any ts project
// Event types have a namespace to aid in finding bugs
export enum EventType {
EXAMPLE = 'namespace:example',
}
const EventHandler = {
callbacks: {} as { [key in EventType]: { [id: string]: Function }},
on: (callerSig: string, type: EventType, callback: Function) => {
if (!EventHandler.callbacks[type]) {
EventHandler.callbacks[type] = {};
}
EventHandler.callbacks[type][callerSig] = callback;
},
once: (callerSig: string, type: EventType, callback: Function) => {
const onceCallback = (...args: any[]) => {
EventHandler.off(callerSig, type);
callback(...args);
};
EventHandler.on(callerSig, type, onceCallback);
},
off: (callerSig: string, type: EventType) => {
if (EventHandler.callbacks[type]) {
delete EventHandler.callbacks[type][callerSig];
}
},
emit: (type: EventType, ...args: any[]) => {
if (EventHandler.callbacks[type]) {
Object.values(EventHandler.callbacks[type]).forEach(callback => {
callback(...args);
});
}
},
emitExcept: (type: EventType, exceptCallerSigs: string[], ...args: any[]) => {
if (EventHandler.callbacks[type]) {
Object.entries(EventHandler.callbacks[type]).forEach(([callerSig, callback]) => {
if (!exceptCallerSigs.includes(callerSig)) {
callback(...args);
}
});
}
}
};
export default EventHandler;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment