简单实现一个观察者模式

function Observer(){this.fns = []}

Observer.prototype = {

  subscribe:function(fn){

     this.fns.push(fn)

  },

  unsubscribe:function(fn){

     this.fns = this.fns.filter((cb)=>{if(cb != fn){return true}})

  },

  update:function(o,thisobj){

    let scope = thisobj || window

    this.fns.forEach((val)=>{

       val.call(scope,o)

    })

  }

}

//以下为举的简单例子

let o = new Observer()

let f1 = function(data){

   console.info(`li:${data}`)

}

let f2 = function(data){

   console.info(`wang:${data}`)

}

let f3 = function(data){

   console.info(`williem:${data}`)

}

o.subscribe(f1)

o.subscribe(f2)

o.subscribe(f3)

o.update("tom回来了")

 

/*输出示例*/

li:tom回来了

wang:tom回来了

williem:tom回来了

o.unsubscribe(f1)

/*输出示例*/

wang:tom回来了

williem:tom回来了

posted @ 2021-01-11 18:23  灏月天染  阅读(156)  评论(0编辑  收藏  举报