Last active
December 24, 2017 06:07
-
-
Save devsnek/6da85dfd8f32b54389676d1c8dc91a14 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
const kMap = Symbol('map'); | |
class EventEmitter { | |
constructor() { | |
this[kMap] = new Map(); | |
} | |
on(event, handler, once = false) { | |
const fn = ({ detail }) => handler.apply(this, detail); | |
this[kMap].set(handler, { fn, once }); | |
return window.addEventListener(event, fn, { once }); | |
} | |
once(event, handler) { | |
return this.on(event, handler, true); | |
} | |
emit(event, ...args) { | |
return window.dispatchEvent(new CustomEvent(event, { detail: args })); | |
} | |
off(event, handler) { | |
const { fn, once } = this[kMap].get(handler); | |
if (!fn) | |
return false; | |
return window.removeEventListener(event, fn, { once }); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment