2020-05-19 05:02:56 -04:00
|
|
|
// Simple event emitter implementation, but has a slightly unusual API for
|
|
|
|
// removing specific listeners. If a specific listener needs to be removed
|
|
|
|
// (instead of all listeners), then it needs to use a "namespace":
|
|
|
|
// Create a listener on the foo event with bar namespace: .on 'foo.bar'
|
|
|
|
// Trigger all events for the foo event (including namespaces): .trigger 'foo'
|
|
|
|
// Remove all listeners for the foo event (including namespaces): .off 'foo'
|
|
|
|
// Remove a listener for the foo event with the bar namespace: .off 'foo.bar'
|
|
|
|
|
2022-08-24 07:49:15 -04:00
|
|
|
export default class EventEmitter {
|
2020-05-19 05:02:56 -04:00
|
|
|
on(event, callback) {
|
|
|
|
if (!this.events) {
|
|
|
|
this.events = {}
|
|
|
|
}
|
2024-05-08 11:04:20 -04:00
|
|
|
let namespace
|
2020-05-19 05:02:56 -04:00
|
|
|
;[event, namespace] = Array.from(event.split('.'))
|
|
|
|
if (!this.events[event]) {
|
|
|
|
this.events[event] = []
|
2018-11-05 05:06:39 -05:00
|
|
|
}
|
2024-05-08 11:04:20 -04:00
|
|
|
this.events[event].push({
|
2020-05-19 05:02:56 -04:00
|
|
|
callback,
|
2021-04-27 03:52:58 -04:00
|
|
|
namespace,
|
2020-05-19 05:02:56 -04:00
|
|
|
})
|
|
|
|
}
|
2018-11-05 05:06:39 -05:00
|
|
|
|
2024-05-08 11:04:20 -04:00
|
|
|
off(event, cb) {
|
2020-05-19 05:02:56 -04:00
|
|
|
if (!this.events) {
|
|
|
|
this.events = {}
|
|
|
|
}
|
2024-05-08 11:04:20 -04:00
|
|
|
if (event) {
|
2020-05-19 05:02:56 -04:00
|
|
|
let namespace
|
2024-05-08 11:04:20 -04:00
|
|
|
;[event, namespace] = event.split('.')
|
|
|
|
if (!this.events[event]) {
|
|
|
|
this.events[event] = []
|
|
|
|
}
|
|
|
|
if (cb) {
|
|
|
|
this.events[event] = this.events[event].filter(e => e.callback !== cb)
|
|
|
|
} else if (!namespace) {
|
2020-05-19 05:02:56 -04:00
|
|
|
// Clear all listeners for event
|
2024-05-08 11:04:20 -04:00
|
|
|
delete this.events[event]
|
2020-05-19 05:02:56 -04:00
|
|
|
} else {
|
|
|
|
// Clear only namespaced listeners
|
2024-05-08 11:04:20 -04:00
|
|
|
this.events[event] = this.events[event].filter(
|
|
|
|
e => e.namespace !== namespace
|
|
|
|
)
|
2018-11-05 05:06:39 -05:00
|
|
|
}
|
2020-05-19 05:02:56 -04:00
|
|
|
} else {
|
|
|
|
// Remove all listeners
|
2024-05-08 11:04:20 -04:00
|
|
|
this.events = {}
|
2018-11-05 05:06:39 -05:00
|
|
|
}
|
2020-05-19 05:02:56 -04:00
|
|
|
}
|
2018-11-05 05:06:39 -05:00
|
|
|
|
2020-05-19 05:02:56 -04:00
|
|
|
trigger(event, ...args) {
|
|
|
|
if (!this.events) {
|
|
|
|
this.events = {}
|
2018-11-05 05:06:39 -05:00
|
|
|
}
|
2024-05-08 11:04:20 -04:00
|
|
|
if (this.events[event]) {
|
|
|
|
this.events[event].forEach(e => e.callback(...args))
|
|
|
|
}
|
2020-05-19 05:02:56 -04:00
|
|
|
}
|
2018-11-05 05:06:39 -05:00
|
|
|
|
2020-05-19 05:02:56 -04:00
|
|
|
emit(...args) {
|
2024-05-08 11:04:20 -04:00
|
|
|
this.trigger(...args)
|
2020-05-19 05:02:56 -04:00
|
|
|
}
|
2020-12-15 05:23:54 -05:00
|
|
|
}
|