All files / utils eventEmitter.ts

100% Statements 13/13
100% Branches 2/2
100% Functions 5/5
100% Lines 13/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56                6x           17x 14x   17x     17x 6x               17x 11x 11x   1x                 18x         6x     6x          
/**
 * 简单的事件发射器
 * 用于组件间通信,如收藏变更通知
 */
 
type EventCallback = (...args: any[]) => void;
 
class EventEmitter {
  private events: Map<string, Set<EventCallback>> = new Map();
 
  /**
   * 订阅事件
   */
  on(event: string, callback: EventCallback): () => void {
    if (!this.events.has(event)) {
      this.events.set(event, new Set());
    }
    this.events.get(event)!.add(callback);
 
    // 返回取消订阅函数
    return () => {
      this.events.get(event)?.delete(callback);
    };
  }
 
  /**
   * 发射事件
   */
  emit(event: string, ...args: any[]): void {
    this.events.get(event)?.forEach((callback) => {
      try {
        callback(...args);
      } catch (error) {
        console.error(`Event handler error for "${event}":`, error);
      }
    });
  }
 
  /**
   * 移除所有事件监听
   */
  clear(): void {
    this.events.clear();
  }
}
 
// 导出单例
export const appEvents = new EventEmitter();
 
// 定义事件名常量
export const APP_EVENTS = {
  FAVORITE_CHANGED: 'favorite_changed',
  LIKE_CHANGED: 'like_changed',
  POST_FAVORITE_CHANGED: 'post_favorite_changed',
} as const;