eventbus.js 1.82 KB
class Bus {
  constructor() {
    this.events = {};
  }

  /**
   * 订阅事件
   * @param {string} event - 事件名称
   * @param {Function} callback - 回调函数
   */
  on(event, callback) {
    if (typeof event !== 'string') {
      console.error('Event name must be a string');
      return;
    }

    if (typeof callback !== 'function') {
      console.error('Callback must be a function');
      return;
    }

    if (this.events[event]) {
      this.events[event].push(callback);
    } else {
      this.events[event] = [callback];
    }

    // 如果是匿名函数就给用户个警告
    if (!callback.name) {
      console.warn('on 接口的 handler 参数推荐使用具名函数。具名函数可以使用 off 接口取消订阅,匿名函数无法取消订阅。');
    }
  }

  /**
   * 触发事件
   * @param {string} event - 事件名称
   * @param {*} data - 传递给回调函数的数据
   */
  emit(event, data) {
    if (!this.events[event]) return;
    
    this.events[event].forEach(callback => {
      if (typeof callback === 'function') {
        callback(data);
      }
    });
  }

  /**
   * 取消订阅事件
   * @param {string} event - 事件名称
   * @param {Function} callback - 要取消的回调函数
   */
  off(event, callback) {
    if (!this.events[event]) return;
    
    if (typeof callback !== 'function') {
      console.error('Callback must be a function');
      return;
    }

    const index = this.events[event].findIndex(item => item === callback);
    if (index !== -1) {
      this.events[event].splice(index, 1);
    }
  }

  /**
   * 获取单例实例
   * @returns {Bus} Bus类的单例实例
   */
  static getInstance() {
    if (!Bus.instance) {
      Bus.instance = new Bus();
    }
    return Bus.instance;
  }
}

// 导出Bus类的单例实例
export default Bus.getInstance();