Created
May 22, 2017 08:33
-
-
Save ijse/466a70b557de3a757bde7cc6ce5f8a76 to your computer and use it in GitHub Desktop.
Simple and no-deps EventEmitter implement for Browser
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
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