Last active
October 23, 2023 02:09
-
-
Save ccnokes/1f00d23a0dc0fe702c6f165c44a02fcb to your computer and use it in GitHub Desktop.
Custom event emitter using native DOM APIs. Read more here: https://cameronnokes.com/blog/build-your-own-event-emitter-using-only-native-dom-apis/
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.target = new EventTarget(); | |
} | |
on(eventName, listener) { | |
return this.target.addEventListener(eventName, listener); | |
} | |
once(eventName, listener) { | |
return this.target.addEventListener(eventName, listener, { once: true }); | |
} | |
off(eventName, listener) { | |
return this.target.removeEventListener(eventName, listener); | |
} | |
emit(eventName, detail) { | |
return this.target.dispatchEvent( | |
new CustomEvent(eventName, { detail, cancelable: true }) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment