Last active
July 24, 2017 09:12
-
-
Save alexjoverm/7648f67d2901780433d04fbbbb60d4e2 to your computer and use it in GitHub Desktop.
Event emitter
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 Emitter { | |
constructor() { | |
this.subscriptions = {} | |
} | |
subscribe(name, cb) { | |
if (!Array.isArray(this.subscriptions[name])) { | |
this.subscriptions[name] = [] | |
} | |
this.subscriptions[name].push(cb) | |
return () => { | |
this.subscriptions[name] = this.subscriptions[name].filter(subCb => subCb !== cb) | |
} | |
} | |
emit(name, ...args) { | |
if (Array.isArray(this.subscriptions[name])) { | |
return this.subscriptions[name].map(cb => cb(...args)) | |
} | |
return [] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment