eventBus.uts 1.98 KB
/**
 * 全局事件总线
 * 用于跨组件通信,解耦业务逻辑
 *
 * 使用方式:
 * import { eventBus } from "@/utils/eventBus.uts"
 * eventBus.emit('xxx', data)
 */

type EventBusCallback = (data?: any) => void

export class EventBus {
	private static instance: EventBus | null = null
	private listeners: Map<string, Array<EventBusCallback>> = new Map()

	static getInstance(): EventBus {
		if (EventBus.instance == null) {
			EventBus.instance = new EventBus()
		}
		return EventBus.instance
	}

	/**
	 * 订阅事件
	 * @param event 事件名称
	 * @param callback 回调函数
	 */
	on(event: string, callback: EventBusCallback): void {
		let callbacks = this.listeners.get(event)
		if (callbacks == null) {
			callbacks = []
			this.listeners.set(event, callbacks)
		}
		callbacks.push(callback)
		console.log(`[EventBus] 订阅事件: ${event}, 当前监听器数量: ${callbacks.length}`)
	}

	/**
	 * 取消订阅
	 * @param event 事件名称
	 * @param callback 回调函数
	 */
	off(event: string, callback: EventBusCallback): void {
		const callbacks = this.listeners.get(event)
		if (callbacks != null) {
			const index = callbacks.indexOf(callback)
			if (index >= 0) {
				callbacks.splice(index, 1)
				console.log(`[EventBus] 取消订阅: ${event}`)
			}
		}
	}

	/**
	 * 发布事件
	 * @param event 事件名称
	 * @param data 事件数据
	 */
	emit(event: string, data?: any): void {
		const callbacks = this.listeners.get(event)
		if (callbacks != null && callbacks.length > 0) {
			for (const cb of callbacks) {
				try {
					cb(data)
				} catch (error) {
					console.error(`[EventBus] 事件回调执行失败: ${event}`, error)
				}
			}
		} else {
			console.warn(`[EventBus] 事件无监听器: ${event}`)
		}
	}

	/**
	 * 清空所有监听器(用于调试或重置)
	 */
	clearAll(): void {
		this.listeners.clear()
		console.log('[EventBus] 已清空所有监听器')
	}
}

// 导出单例实例
export const eventBus = EventBus.getInstance()
export default eventBus