2017-07-06 06:49:33 +00:00
|
|
|
export default class EventEmitter {
|
|
|
|
listeners = {}
|
|
|
|
|
|
|
|
on (event, cb) {
|
|
|
|
if (!this.listeners[event]) {
|
|
|
|
this.listeners[event] = new Set()
|
|
|
|
}
|
|
|
|
|
2017-07-09 03:46:53 +00:00
|
|
|
if (this.listeners[event].has(cb)) {
|
2018-10-26 17:28:10 +00:00
|
|
|
throw new Error(`Listener already exists for router event: \`${event}\``)
|
2017-07-09 03:46:53 +00:00
|
|
|
}
|
|
|
|
|
2017-07-06 06:49:33 +00:00
|
|
|
this.listeners[event].add(cb)
|
2018-08-01 12:43:25 +00:00
|
|
|
return this
|
2017-07-06 06:49:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
emit (event, ...data) {
|
2018-08-01 12:43:25 +00:00
|
|
|
const listeners = this.listeners[event]
|
|
|
|
const hasListeners = listeners && listeners.size
|
|
|
|
if (!hasListeners) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
listeners.forEach(cb => cb(...data)) // eslint-disable-line standard/no-callback-literal
|
|
|
|
return true
|
2017-07-06 06:49:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
off (event, cb) {
|
|
|
|
this.listeners[event].delete(cb)
|
2018-08-01 12:43:25 +00:00
|
|
|
return this
|
2017-07-06 06:49:33 +00:00
|
|
|
}
|
|
|
|
}
|