首页 > 其他 > 详细

发布订阅模式

时间:2021-05-12 14:38:37      阅读:25      评论:0      收藏:0      [点我收藏+]
// 主题
class Dep {
  constructor(callback) {
    this.subs = [] // 主题的订阅者
    this.callback = callback
    // console.log(‘callback‘, callback)
  }

  // 添加订阅者
  addSub(sub) {
    console.log(‘sub‘,sub)
    this.subs.push(sub)
    return this
  }

  // 主题更新通知---调用订阅者update,通知所有订阅者
  notify() {
    this.subs.forEach(item => {
    item.update(this.callback)
  });
  }
}

// 订阅者
class Sub {
  constructor(val) {
    this.val = val
  }

  update(callback) {
    // console.log(‘update‘, callback)
    this.val = callback(this.val)
    console.log(‘更新之后:‘, this.val)
  }
}

// 发布者
class Pub {
  constructor() {
    this.deps = [] // 发布的主题列表
  }

  // 添加主题
  addDep(dep) {
    this.deps.push(dep)
  }

  // 移除主题
  removeDep(dep) {
    let index = this.deps.indexOf(dep)
    if(index !== -1) {
      this.deps.splice(index, 1)
      return true
    } else {
      return false
    }
  }

  // 更新主题
  publish(dep) {
    this.deps.forEach(item => item == dep && item.notify());
  }
}

// 新建主题, 给主题中加订阅者
let dep1 = new Dep(item => item * item)
// console.log(dep1)
// dep1.addSub(new Sub(1)).addSub(new Sub(2)).addSub(new Sub(3))
// dep1.addSub(new Sub(1))
console.log(dep1.addSub(new Sub(1)))

// 新建发布者
let pub = new Pub()
// 添加主题
pub.addDep(dep1)

// 发布者发布,通知这个主题的所有订阅更新
pub.publish(dep1)

 

发布订阅模式

原文:https://www.cnblogs.com/Roxxane/p/14757990.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!