Skip to content

Instantly share code, notes, and snippets.

@demoon84
Created September 27, 2024 05:22
Show Gist options
  • Save demoon84/4d391b2fde793269df8cff7c893ba791 to your computer and use it in GitHub Desktop.
Save demoon84/4d391b2fde793269df8cff7c893ba791 to your computer and use it in GitHub Desktop.
export class Emitter {
constructor() {
this.store = {};
}
on(eventList, handler) {
if (typeof handler !== 'function') {
throw new Error('Handler must be a function');
}
eventList.split(' ').forEach((event) => {
if (!this.store[event]) this.store[event] = [];
if (!this.store[event].includes(handler)) {
this.store[event].push(handler);
}
});
}
once(eventList, handler) {
const wrapper = (...args) => {
handler.apply(this, args);
this.off(eventList, wrapper);
};
this.on(eventList, wrapper);
}
off(name, handler) {
if (this.store[name]) {
this.store[name] = this.store[name].filter((h) => h !== handler);
}
}
offAll(eventList) {
eventList.split(' ').forEach((event) => {
if (!this.store[event]) return;
delete this.store[event];
});
}
emit(name, payload) {
if (!this.store[name]) return;
this.store[name].forEach(async (handler) => {
await handler.apply(this, [{...payload}]);
});
}
clear() {
this.store = {};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment