/
bearury
/
ui-kit-ce
Обзор
Документация
Войти
/
bearury
/
ui-kit-ce
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
develop
packages/utils/src/eventManager/EventManager.ts
98 строк
2 KB
zavyalov.d.o
refactor(tabs): устранение eslint warnings
04 мар 2025, 16:27
04 мар 2025, 16:27
c563ca2
Код
Авторство
О чём код?
/* eslint-disable @typescript-eslint/no-explicit-any */ type Callback = (args: any) => void type On<R> = (event: string, callback: Callback) => R type Emit = (event: string, args?: any) => void type Off<R> = (event: string, callback?: Callback) => R export interface EventManagerI { /** * * @inner */ eventList: Map<string, Callback[]> /** * * @inner */ eventEmitQueue: Map<string, Array<ReturnType<typeof setTimeout>>> /** * * @inner */ on: On<this> /** * * @inner */ off: Off<this> cancelEmit(event: string): this /** * * @inner */ emit: Emit } class EventManagerEntity implements EventManagerI { eventList: Map<string, Callback[]> eventEmitQueue: Map<string, NodeJS.Timeout[]> constructor() { this.eventList = new Map() this.eventEmitQueue = new Map() } public on(event: string, callback: Callback) { if (!this.eventList.has(event)) { this.eventList.set(event, []) } this.eventList.get(event)?.push(callback) return this } public off(event: string, callback?: Callback) { if (callback) { const newCallbacks = this.eventList .get(event) ?.filter((cb) => cb !== callback) this.eventList.set(event, newCallbacks ?? []) } else { this.eventList.delete(event) } return this } public cancelEmit(event: string) { const timeoutIds = this.eventEmitQueue.get(event) if (timeoutIds) { timeoutIds.forEach(clearTimeout) this.eventEmitQueue.delete(event) } return this } public emit(event: string, ...args: unknown[]) { this.eventList.get(event)?.forEach((callback: Callback) => { const timeoutId = setTimeout(() => { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore callback(...args) }, 0) if (!this.eventEmitQueue.has(event)) { this.eventEmitQueue.set(event, []) } this.eventEmitQueue.get(event)?.push(timeoutId) }) } } export const eventManager = { createInstance(): EventManagerI { return new EventManagerEntity() }, }