39 lines
869 B
TypeScript
39 lines
869 B
TypeScript
export type EventHandler = (...args: any[]) => void;
|
|
|
|
export class SimpleEventEmitter {
|
|
private _handlers: { [x: string]: EventHandler[] } = {};
|
|
|
|
on(event: string, fn: EventHandler) {
|
|
if (typeof fn !== 'function') {
|
|
return;
|
|
}
|
|
|
|
if (!this._handlers[event]) {
|
|
this._handlers[event] = [];
|
|
}
|
|
|
|
this._handlers[event].push(fn);
|
|
}
|
|
|
|
emit(event: string, ...args: any[]): void {
|
|
if (!this._handlers[event]) {
|
|
return;
|
|
}
|
|
|
|
this._handlers[event]
|
|
.filter((fn) => fn && typeof fn === 'function')
|
|
.forEach((fn) => fn(...args));
|
|
}
|
|
|
|
removeEventListener(event: string, fn: EventHandler): void {
|
|
if (!this._handlers[event] || typeof fn !== 'function') {
|
|
return;
|
|
}
|
|
|
|
const indexOf = this._handlers[event].indexOf(fn);
|
|
if (indexOf > -1) {
|
|
this._handlers[event].splice(indexOf, 1);
|
|
}
|
|
}
|
|
}
|