简易观察者模式

var Event = {
  on(event,callback){
    if(!this.handles){
      this.handles = {};
    }
    if(!this.handles[event]){
      this.handles[event] = [];
    }
    this.handles[event].push(callback);
  },
  emit(event){
    if(this.handles[event]){
      for (var i = 0; i < this.handles[event].length; i++) {
        this.handles[event][i]()
      }
    }
  },
  off(event,callback){
    for (var i = 0; i < this.handles[event].length; i++) {
      var a = this.handles[event][i].toString();
      var b = callback.toString();
      if(a == b){
        this.handles[event].splice(i,1);
        break;
      }
    }
  }
};

posted on 2017-09-25 16:06  vsmart  阅读(108)  评论(0编辑  收藏  举报