发布订阅模式

// 主题
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)