Skip to content

Instantly share code, notes, and snippets.

@vvscode
Created September 4, 2024 11:39
Show Gist options
  • Save vvscode/eaa7c42c38600633e1fd9efe69525c75 to your computer and use it in GitHub Desktop.
Save vvscode/eaa7c42c38600633e1fd9efe69525c75 to your computer and use it in GitHub Desktop.
EventEmitter.js
export class EventEmitter {
listeners = new Map();
on(eventName, cb) {
if (!this.listeners.has(eventName)) {
this.listeners.set(eventName, new Set([]));
}
this.listeners.get(eventName)?.add(cb);
}
off(eventName, cb) {
if (this.listeners.has(eventName)) {
this.listeners.get(eventName)?.delete(cb);
}
}
trigger(eventName, data) {
this.listeners.get(eventName)?.forEach((el) => {
try {
el(data);
} catch (e) {}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment