手写一个发布订阅

    1:所有的发布订阅就是一个对象。
    class Obersve {
      event={}  //等价于下面的constructor
      // constructor() {
      //   this.event = {}
      // }
      subscribe(type, fn) { //订阅
        if (Object.keys(this.event).includes(type)) { 
          this.event[type].push(fn)
        } else {
          this.event[type] = [fn]
        }
      }
      publish(type, args = {}) {  //发布
        if (this.event[type]) {
          this.event[type].map(item => {
            item.call(this, { type,args}) 
          })
        }
      }
    }
    const ober = new Obersve()
    ober.subscribe('aaa', function (e) {
      console.log(`事件: ${e.type}`)
      console.log(`消息: ${e.args.message}`)
    })
    ober.publish('aaa', {
      message: '亮哥'
    })
原文地址:https://www.cnblogs.com/binglove/p/13305054.html