Skip to content

Instantly share code, notes, and snippets.

@ccnokes
Last active October 23, 2023 02:09
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ccnokes/1f00d23a0dc0fe702c6f165c44a02fcb to your computer and use it in GitHub Desktop.
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/
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