自定义事件实现bind,unbind,trigger方法

class Emit {
  constructor(){
    this.name = 'Emit';
    this._linstener = {};
  }
  bind(type,callback){
    let linstener = this._linstener[type] || [];
    linstener.push(callback);
    this._linstener[type] = linstener;
  }
  trigger(type,callback){
    if(typeof type !== 'string') throw new Error('EventName Error');
    if(typeof callback === 'function'){
      let args = Array.prototype.slice.call(arguments,2);
      this._linstener[type].forEach(function(item,index){
        if(item === callback){
          item.apply(this,args);
          return false;
        }
      }.bind(this))
    }else{
      let args = Array.prototype.slice.call(arguments,1);
      this._linstener[type].forEach(function(item,index){
        if(typeof item !== 'function') throw new Error('CallBack is not a Function');
        item.apply(this,args);
      }.bind(this))
    }
  }
  unbind(type,callback){
    if(typeof type !== 'string') throw new Error('EventName Error');
    if(this._linstener[type] === undefined) return;
      if(typeof fn === 'function'){
        this._linstener[type].forEach(function(item,index){
        if(item === fn){
          this._linstener[type].splice(index,1);
          return false;
        }
      }.bind(this))

      }else{
        delete this._linstener[type];
      }  
  }
}


    //测试
    var event = new Emit();
    //console.log(event)
    function a(a){
      alert(a)
    }
    event.bind('click',a)
    console.log(event)
    function b(b){
      alert(b)
    }
    event.bind('click',b)
    //event.unbind('click',b)
    event.trigger('click',a,'a')
    event.trigger('click',b,'b')
    console.log(event)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容