Skip to content

Instantly share code, notes, and snippets.

@ijse
Created May 22, 2017 08:33
Show Gist options
  • Save ijse/466a70b557de3a757bde7cc6ce5f8a76 to your computer and use it in GitHub Desktop.
Save ijse/466a70b557de3a757bde7cc6ce5f8a76 to your computer and use it in GitHub Desktop.
Simple and no-deps EventEmitter implement for Browser
export default class EventBus {
constructor () {
this.bus = document.createElement('span')
}
on (eventName, fn) {
const handler = event => {
fn && fn(...event.params)
}
this.bus.addEventListener(eventName, handler)
fn.__off__ = () => {
this.bus.removeEventListener(eventName, handler)
}
}
emit (eventName, ...args) {
const event = new window.Event(eventName)
event.params = args || []
this.bus.dispatchEvent(event)
}
off (eventName, fn) {
typeof fn.__off__ === 'function' && fn.__off__()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment