Skip to content

Instantly share code, notes, and snippets.

@alexjoverm
Last active July 24, 2017 09:12
Show Gist options
  • Save alexjoverm/7648f67d2901780433d04fbbbb60d4e2 to your computer and use it in GitHub Desktop.
Save alexjoverm/7648f67d2901780433d04fbbbb60d4e2 to your computer and use it in GitHub Desktop.
Event emitter
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