// event-bus.js（改进版）
const eventBus = {
  events: {},
  cachedEvents: {}, // 缓存已触发的事件
  
  // 监听事件（支持获取历史缓存事件）
  on(event, callback, getCached = true) {
    if (!this.events[event]) {
      this.events[event] = [];
    }
    this.events[event].push(callback);
    
    // 如果有缓存事件，立即执行回调
    if (getCached && this.cachedEvents[event]) {
      callback(this.cachedEvents[event]);
    }
  },
  
  // 触发事件（缓存最新数据）
  emit(event, data) {
    this.cachedEvents[event] = data;
    if (this.events[event]) {
      this.events[event].forEach(callback => callback(data));
    }
  },
  
  // 清除缓存事件
  clear(event) {
    if (event) {
      delete this.cachedEvents[event];
    } else {
      this.cachedEvents = {};
    }
  }
};

export default eventBus;