tiptap/packages/core/src/EventEmitter.ts

43 lines
856 B
TypeScript
Raw Normal View History

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
2021-01-28 16:50:17 +08:00
public on(event: string, fn: Function): this {
2020-09-24 15:35:18 +08:00
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
}
2021-01-28 16:50:17 +08:00
protected emit(event: string, ...args: any): this {
2020-09-24 15:35:18 +08:00
const callbacks = this.callbacks[event]
2020-04-02 03:15:23 +08:00
if (callbacks) {
callbacks.forEach(callback => callback.apply(this, args))
}
return this
}
2021-01-28 16:50:17 +08:00
public off(event: string, fn?: Function): this {
2020-09-24 15:35:18 +08:00
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
}
2021-01-28 16:50:17 +08:00
protected removeAllListeners(): void {
2020-09-24 15:35:18 +08:00
this.callbacks = {}
2020-04-02 03:15:23 +08:00
}
}