发布订阅者模式

<script>
  // 事件触发器
  class EventEmitter {
    constructor () {
      // { 'click': [fn1, fn2], 'change': [fn] }
      this.subs = Object.create(null)
    }

    // 注册事件
    $on (eventType, handler) {
      this.subs[eventType] = this.subs[eventType] || []
      this.subs[eventType].push(handler)
    }

    // 触发事件
    $emit (eventType) {
      if (this.subs[eventType]) {
        this.subs[eventType].forEach(handler => {
            handler()
        })
      }
    }
}

// 测试
let em = new EventEmitter()
em.$on('click', () => {
  console.log('click1')
})
em.$on('click', () => {
  console.log('click2')
})

em.$emit('click')
</script>
posted @ 2022-04-18 10:42  有肌肉的小眼睛  阅读(14)  评论(0编辑  收藏  举报