手写EventEmitter

188 阅读1分钟

实现一个EventEmitter


class EventEmitter {
  
  constructor() {
    this.events = {}
  }

  on(type, handler) {
    if(!this.events[type]) {
      this.events[type] = []
    }
    this.events[type].push(handler)
  }
  
  off(type, handler) {
    if(!this.events[type]) return

    this.events[type] = this.events[type].filter(fn => fn !== handler && fn.handler !== handler)
  }
  
  once(type, handler) {
    const self = this
    function wrapHandler(...args) {
      handler.apply(this, args)
      self.off(type, wrapHandler)
    }
    wrapHandler.handler = handler
    self.off(type, wrapHandler)
  }
  
  emit(type, ...args) {
    if(this.events[type]) {
      this.events[type].forEach(fn => {
        fn.apply(this, args)
      })
    }
  }
}