pubsub.ts 1.87 KB
/**
 * 发布订阅模式实现
 */
export class PubSub {
  private subscribers: Record<string, Function[]> = {};

  /**
   * 订阅事件
   * @param {string} event 事件名称
   * @param {Function} callback 回调函数
   * @returns {Function} 取消订阅的函数
   */
  subscribe(event: string, callback: Function): Function {
    if (!this.subscribers[event]) {
      this.subscribers[event] = [];
    }
    this.subscribers[event].push(callback);

    // 返回取消订阅的函数
    return () => {
      this.subscribers[event] = this.subscribers[event].filter(cb => cb !== callback);
    };
  }

  /**
   * 发布事件
   * @param {string} event 事件名称
   * @param {...any} args 传递给订阅者的参数
   */
  publish(event: string, ...args: any[]): void {
    if (!this.subscribers[event]) {
      return;
    }
    this.subscribers[event].forEach(callback => {
      try {
        callback(...args);
      } catch (error) {
        console.error('\x1b[31m❌ %s\x1b[0m', `Error in event handler for ${event}:`, error);
      }
    });
  }

  /**
   * 取消订阅
   * @param {string} event 事件名称
   * @param {Function} callback 回调函数,如果不提供则取消该事件的所有订阅
   */
  unsubscribe(event: string, callback?: Function): void {
    if (!this.subscribers[event]) {
      return;
    }
    if (!callback) {
      delete this.subscribers[event];
    } else {
      this.subscribers[event] = this.subscribers[event].filter(cb => cb !== callback);
    }
  }

  /**
   * 获取事件的所有订阅者
   * @param {string} event 事件名称
   * @returns {Function[]} 订阅者列表
   */
  getSubscribers(event: string): Function[] {
    return this.subscribers[event] || [];
  }

  /**
   * 清空所有订阅
   */
  clear(): void {
    this.subscribers = {};
  }
}

// 创建全局事件总线实例
export const createEventBus = () => new PubSub();