Web Development

/ 0评 / 0/ 最后更新:2021-12-15
源码理解:手写EventBus
class EventBus {
  map = {} 
  
  on(type, handler) {
    this.map[type] = (this.map[type] || []).concat(handler)
  }
  
  fire(type, data) {
    this.map[type] && this.map[type].forEach(handler => handler(data))
  }
  
  off(type, handler) {
    if(this.map[type]) {
      if(!handler) {
        delete this.map[type]
      } else {
        let index = this.map[type].indexOf(handler)
        this.map[type].splice(index, 1)
      }
    }
  }
}

const eventBus = new EventBus()

eventBus.on('click:btn', data => {
  console.log(data)
})

eventBus.fire('click:btn', {a: 1, b: 2})
eventBus.off('click:btn')
eventBus.fire('click:btn', {a: 1, b: 2})
0

Leave a Reply

Your email address will not be published. Required fields are marked *