2020-04-02 03:15:23 +08:00
|
|
|
export default class EventEmitter {
|
|
|
|
|
2020-09-24 15:35:18 +08:00
|
|
|
private callbacks: { [key: string]: Function[] } = {}
|
2020-04-02 03:15:23 +08:00
|
|
|
|
2020-09-24 15:35:18 +08:00
|
|
|
public on(event: string, fn: Function) {
|
|
|
|
if (!this.callbacks[event]) {
|
|
|
|
this.callbacks[event] = []
|
2020-04-02 03:15:23 +08:00
|
|
|
}
|
|
|
|
|
2020-09-24 15:35:18 +08:00
|
|
|
this.callbacks[event].push(fn)
|
2020-09-24 06:29:05 +08:00
|
|
|
|
2020-04-02 03:15:23 +08:00
|
|
|
return this
|
|
|
|
}
|
|
|
|
|
2020-09-24 15:35:18 +08:00
|
|
|
protected emit(event: string, ...args: any) {
|
|
|
|
const callbacks = this.callbacks[event]
|
2020-04-02 03:15:23 +08:00
|
|
|
|
|
|
|
if (callbacks) {
|
|
|
|
callbacks.forEach(callback => callback.apply(this, args))
|
|
|
|
}
|
|
|
|
|
|
|
|
return this
|
|
|
|
}
|
|
|
|
|
2020-09-24 15:35:18 +08:00
|
|
|
public off(event: string, fn?: Function) {
|
|
|
|
const callbacks = this.callbacks[event]
|
2020-04-02 03:15:23 +08:00
|
|
|
|
|
|
|
if (callbacks) {
|
|
|
|
if (fn) {
|
2020-09-24 15:35:18 +08:00
|
|
|
this.callbacks[event] = callbacks.filter(callback => callback !== fn)
|
2020-04-02 03:15:23 +08:00
|
|
|
} else {
|
2020-09-24 15:35:18 +08:00
|
|
|
delete this.callbacks[event]
|
2020-04-02 03:15:23 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return this
|
|
|
|
}
|
|
|
|
|
2020-09-24 15:35:18 +08:00
|
|
|
protected removeAllListeners() {
|
|
|
|
this.callbacks = {}
|
2020-04-02 03:15:23 +08:00
|
|
|
}
|
|
|
|
}
|