-
-
Save Xvezda/03f4b1aac0aae724f981f7d933d7617b 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