首页 > 其他 > 详细

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

时间:2020-07-26 19:48:10      阅读:45      评论:0      收藏:0      [点我收藏+]
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‘);    
}

 

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!