Created
September 27, 2024 05:22
-
-
Save demoon84/4d391b2fde793269df8cff7c893ba791 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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