js 发布订阅模式

请添加图片描述
发布者与订阅者之间没有关联,由调度中心来处理事件。
订阅者通过on去订阅事件,发布者通过emit去发布一个事件。
发布者不需要知道谁对这个事件做出回应,订阅者不需要知道事件什么时候触发。

可以多个订阅者订阅一个发布者的事件,发布者与订阅者是一对多的依赖关系。

class EventBus {
  // 事件列表
  list = {}

  // 订阅事件
  on(key, fn) {
    if (!this.list[key]) {
      // 一个发布事件类型的多个订阅事件
      this.list[key] = []
    }
    this.list[key].push(fn)
  }

  // 解除订阅事件
  off(key, fn) {
    let fns = this.list[key]
    if (!fns) return false
    if (!fn) {
      // 解除一个发布事件类型的所有订阅事件
      fns && (fns.length = 0)
    } else {
      fns.forEach((cb, i) => {
        if (cb === fn) {
          fns.splice(i, 1)
        }
      })
    }
  }

  // 发布事件
  emit() {
    let key = [].shift.call(arguments)
    let fns = this.list[key]
    if (!fns || fns.length === 0) {
      // 没有订阅事件可以触发
      return false
    }
    fns.forEach((fn) => {
      fn.apply(this, arguments)
    })
  }
}

测试代码

const eventBus = new EventBus()

class Publisher {
  constructor() {
    this.lowPrice()
  }

  lowPrice() {
    eventBus.emit('ready', 100)
  }
}

class Subscriber {
  constructor() {
    this.getLowPrice()
  }

  getLowPrice() {
    eventBus.on('ready', (data) => {
      console.log('ready', data)
    })
  }
}

const subscriber = new Subscriber()
const publisher = new Publisher()

参考
设计模式 - js 发布订阅模式

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值