设计模式 --kkb

瘦欲@ 提交于 2019-12-11 15:18:05

设计模式概念

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

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

 

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

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')

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

1

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!