发布订阅模式

19 阅读1分钟
class PubSub{
  constructor(){
    this.events = {}
  }

  // 订阅
  subscribe(name,cb){

    if(!this.events[name]) {
      this.events[name] = [];
    }
    this.events[name].push(cb)
    return () => this.unsubscribe()
  }

  // 发布
  publish(name,...args){
    if(!this.events[name]) {
      this.events[name] = [];
    }
    this.events[name].forEach(cb=>cb(...args))
  }

  // 取消订阅
  unsubscribe(name,cb){
    console.log('this.events', this.events)
    if(this.events[name]) {
      this.events[name] = this.events[name].filter(item=>item!==cb)
    }
  }

}


const ps = new PubSub();
// 订阅
const sub_off = ps.subscribe('login', (user)=>{
  console.log('Hi', user.name)
})
// 发布
ps.publish('login',{name:'zxj'})


// 取消订阅
sub_off();