js中的观察者模式

什么事观察者模式:

  这是一种创建松散耦合代码的技术。它定义对象间 一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都将得到通知。由主体和观察者组成,主体负责发布事件,同时观察者通过订阅这些事件来观察该主体。主体并不知道观察者的任何事情,观察者知道主体并能注册事件的回调函数。

代码:

function EventT(){

  this.handlers = {};

}

EventT.prototype = {

  custructor : EventT,

  addHanler : function(type,handler){

    if(typeof this.handlers[type] == 'undefined'){

      this.handlers[type] = [];

    }

    this.handlers[type].push(handler);

  },

  fire:function(event){

    if(!event.target){

      event.target = this;

    }

    if(this.handlers[event.type] instanceof Array){

      var handlers = this.handlers[event.type];

      for(var i=0,len = handlers.length;i<len;i++){

        handlers[i](event)

      }

    }

  },

  removeHandler:function(type,handler){

    if(this.handlers[type] instanceof Array){

      var handlers = this.handlers[type];

      for(var i=0,len=handlers.length;i<len;i++){

        if(handlers[i] === handler){

          break;

        }

      }

      handlers.splice(i,1)

    }

  }

}

大概意思就是,创建一个事件管理器。handles是一个存储事件处理函数的对象。

addHandle:是添加事件的方法,该方法接收两个参数,一个是要添加的事件的类型,一个是这个事件的回调函数名。调用的时候会首先遍历handles这个对象,看看这个类型的方法是否已经存在,如果已经存在则添加到该数组,如果不存在则先创建一个数组然后添加。

fire方法:是执行handles这个对象里面的某个类型的每一个方法。

removeHandle:是相应的删除函数的方法。

新建两个对象:

var person1 = {};

var person2 ={};

Object.assign(person1,Event);

Object.assign(person2,Event);

person1.on('call1', function () {
    console.log('person1');
});
person2.on('call2', function () {
    console.log('person2');
});
person1.emit('call1'); // 输出 'person1'
person1.emit('call2'); // 没有输出
person2.emit('call1'); // 没有输出
person2.emit('call2'); // 输出 'person2'
原网址:https://www.cnblogs.com/LuckyWinty/p/5796190.html
原文地址:https://www.cnblogs.com/Mrkaikai/p/9499512.html