美文网首页
4. 观察者模式

4. 观察者模式

作者: zdxhxh | 来源:发表于2019-11-28 16:25 被阅读0次

    订阅发布模式,对前端来说这已经是老生常谈了

    观察者模式,又称为订阅发布模式,其实质就是在内存中开辟一个对象(事件车),专门用于接口的注册(订阅)与触发(发布)

    以前的憨憨前端工程师就是这样的方法在脚本中注册大量的接口,从而实现开发人员可以在闭包模块中调用其他人的接口,最后导致这个事件车拥有大量的接口,后期维护相当复杂

    另一个方面,事件车常常用于某些框架的组件通信

    class EventEmiter { 
      constructor() {
        this.cache = [] 
      }
      emit(type,...args) {
        if(this.cache[type] && this.cache[type].length > 0) {
           let i = -1,len = this.cache[type].length
           while(++i < len ) {
              this.cache[type][i].call(null,...args)
           }
        } else {
          return new TypeError('this cache '+ type +' is null')
        }
      }
      register(type,fn){
        if(this.cache[type] === undefined){
          this.cache[type] = [fn]
        } else {
          this.cache[type].push(fn)
        }
        return ()=> {
          this.remove(type,fn)
        }
      }
      remove(type,fn){
        if(!this.cache[type] || this.cache[type].length === 0)  {
          return new TypeError('this cache '+ type +' is null')
        }
        let i= this.cache[type].length
        while(--i>=0 ) {
          if(this.cache[type] === fn ) {
            return this.cache.splice(i,1)
          }
        } 
      }
    }
    

    相关文章

      网友评论

          本文标题:4. 观察者模式

          本文链接:https://www.haomeiwen.com/subject/qnmbwctx.html