设计模式 --kkb

设计模式概念

前人总结的代码最佳实践。

设计模式是一套被反复使用、多人知晓的、经过分类的、代码设计经验的总结。

订阅/发布模式(观察者模式)

class Event{
  constructor(){
    this.callbacks = {}
  }
  $on(name, fn){ // 监听
    // if(!this.callbacks[name]){
    //   this.callbacks[name] = []
    // }
    // this.callbacks[name].push(fn)

    // 上述代码的简写
    (this.callbacks[name] || (this.callbacks[name]=[])).push(fn)
  }
  $emit(name, arg){
    const cbs = this.callbacks[name]
    if(cbs){
      cbs.forEach(c=>{
        c.call(this, arg)
      })
    }
  }
  $off(name){
    this.callbacks[name] = null
  }
}

let event = new Event()
event.$on('event1', arg => {
  console.log('event1触发', arg)
})
event.$on('event1', arg => {
  console.log('又一个event1触发', arg)
})
event.$on('event2', arg => {
  console.log('event2触发', arg)
})

event.$emit('event1', 'myArg')
event.$emit('event2', 'myArg2')
event.$off('event1')
event.$emit('event1', 'myArg')
扫描二维码关注公众号,回复: 8153466 查看本文章

1

猜你喜欢

转载自www.cnblogs.com/haishen/p/12022568.html