发布订阅模式简单实现

版权声明: https://blog.csdn.net/weixin_41826907/article/details/80518321

代码

export default class Oberver {
  // 定义一个事件容器
  event = {}

  subscribe (type, fn) {
    // 消息类型不存在
    if (typeof this.event[type] === 'undefined') {
      this.event[type] = [fn]
    // 存在,将fn推入事件队列
    } else {
      this.event[type].push(fn)
    }
  }

  publish (type, args = {}) {
    // 消息类型没人订阅
    if (!this.event[type]) return

    let i = 0
    let len = this.event[type].length
    for (; i < len; i++) {
      // 依次执行事件队列(发布)
      this.event[type][i].call(this, {type, args})
    }
  }
}

测试

const ober = new Oberver()
ober.subscribe('time', function (e) {
  console.log(`事件: ${e.type}`)
  console.log(`消息: ${e.args.message}`)
})

ober.subscribe('js', function (e) {
  console.log(`事件: ${e.type}`)
  console.log(`消息: ${e.args.message}`)
})

ober.publish('time', {message: '我订阅了time'})

效果
这里写图片描述

猜你喜欢

转载自blog.csdn.net/weixin_41826907/article/details/80518321