Last active
May 16, 2023 13:21
-
-
Save dwaps/4eec95d33e322c6516b1dd1ea0a3c7d4 to your computer and use it in GitHub Desktop.
Node : Création d'un EventEmitter
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
class EventEmitter { | |
constructor() { | |
this.events = {}; | |
} | |
on(eventName, listener) { | |
this.events[eventName] = this.events[eventName] || []; | |
this.events[eventName].push(listener); | |
} | |
once(eventName, listener) { | |
listener.once = true; | |
this.on(eventName, listener); | |
} | |
emit(eventName, ...args) { | |
const eventListeners = this.events[eventName]; | |
if (eventListeners) { | |
eventListeners.forEach((listener) => listener(...args)); | |
eventListeners.forEach((listener, index) => { | |
if (listener.once) { | |
eventListeners.splice(index, 1); | |
} | |
}); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment