EventBus事件通信

538 阅读1分钟

代码

/**
 * EventBus
 * 可以实现对象之间的通信,当数据或某些特性发生改变时,能自动监听事件作出一些改变
 */
class EventBus {
  constructor(name = 'EventBus') {
    this.name = name
    // 单例模式
    this._events = this._events || new Object() // 存储自定义事件
  }
  /**
   * 注册事件
   * @param {String} eventName 绑定事件的名字
   * @param {Function} callback 执行的方法
   */
  on(eventName, callback) {
    // 判断事件是否存在
    if (!this._events[eventName]) {
      this._events[eventName] = [callback]
    } else {
      this._events[eventName].push(callback)
    }
  }

  /**
   * 绑定一次后销毁
   * @param {String} eventName 绑定事件的名字
   * @param {Function} callback 
   */
  once(eventName, callback) {
    let once = (...args) => {
      this.off(eventName)
      callback(...args)
    }
    this.on(eventName, once)
  }

  /**
   * 销毁事件
   * @param {String} eventName 销毁事件的名字
   */
  off(eventName) {
    if (this._events[eventName]) {
      delete this._events[eventName]
      console.log(`${eventName}<==销毁`)
    }
  }
  /**
   * 触发事件
   * @param {String} eventName 绑定事件的名字
   * @param  {...any} args 传递的参数
   */
  emit(eventName, ...args) {
    if (this._events[eventName]) {
      this._events[eventName].forEach(callback => {
        callback([...args]);
      })
    } else {
      console.error(`${eventName}<==绑定事件不存在或已经销毁`)
    }
  }
}


let emiter = new EventBus()

emiter.on('test', args => {
  console.log(args);
})
emiter.on('test', args => {
  console.log(args.join());
})
emiter.on('test1', args => {
  console.log(args.join());
})

// 触发事件
emiter.emit('test', 11, 11, 11)
emiter.off('test')
emiter.emit('test', 11, 12, 31)

注意事项

使用场景