Last active
February 20, 2020 23:02
-
-
Save ZeroDragon/1729ea65dd434dee59d6afdd2f42a1ef to your computer and use it in GitHub Desktop.
Browser side eventEmitter
This file contains hidden or 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.DOM = document.createElement("p") | |
} | |
on(channel, fn) { | |
this.DOM.addEventListener(channel, event => { | |
fn(event.detail) | |
}) | |
} | |
dispatch(channel, data) { | |
const detail = typeof data === 'string' ? data : JSON.stringify(data) | |
this.DOM.dispatchEvent(new CustomEvent(channel, { detail })) | |
} | |
} | |
// Usage | |
const myEvent = new EventEmitter() | |
myEvent.on('message', console.log) | |
myEvent.dispatch('message', 'hi browser side events') // "hi browser side events" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
flexeas bien cabrón, dude. Tengo q mejorar mucho