码迷,mamicode.com
首页 > 其他好文 > 详细

面向对象开发之自定义事件

时间:2020-07-26 19:05:55      阅读:61      评论:0      收藏:0      [点我收藏+]

标签:cal   let   定义   事件   clu   func   click   监听   define   

class Event {
  constructor(){
    this.handlers = {}; // 记录所有的事件及处理函数
    // {
    //   click: [fn1, fn2],
    //   mouseover: [fn3, fn4],
    // };
    
  }

  /**
   * on 添加事件监听
   * @param type    要添加的事件类型
   * @param handler 要添加的的事件处理函数
   * @param once    是否只执行一次
   */
  on(type, handler, once = false) {
    if (!this.handlers[type]) {
      this.handlers[type] = [];
    }

    if (this.handlers[type].includes(handler)) {
      this.handlers[type].push(handler);
      handlers.once = once;
    }
  }

  /**
   * off取消事件监听
   * @param type    要取消的事件类型
   * @param handler 要取消的事件处理函数,如果不传则清除该类型所有函数
   */
  off(type, handler) {
    if (this.handlers[type]) {
      if (handler === undefined) {
        this.handlers[type] = [];
      } else {
        this.handlers[type] = this.handlers[type].filter(f => f !== handler)
      }
    }
  }

  /**
   * once 该函数只执行一次
   * @param type    要添加的事件类型
   * @param handler 要添加的的事件处理函数
   */
  once() {
    this.on(type, handler, true);
  }

  /**
   * trigger 执行该函数
   * @param type      要执行的函数类型
   * @param eventData 事件对象
   * @param point this执行
   */
  trigger(type, eventData = {}, point = this) {
    if (this.handlers[type]) {
      this.handlers[type].forEach((f) => {
        f.call(point, eventData);
        if (f.once) {
          this.off(type, f);
        }
      })
    }
  }

}
let el = new Event();
el.on(‘click‘, fn);
function fn() {
  console.log(‘11‘);    
}

 

面向对象开发之自定义事件

标签:cal   let   定义   事件   clu   func   click   监听   define   

原文地址:https://www.cnblogs.com/yxfboke/p/13380241.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!