美文网首页
JavaScript实现一个自定义事件函数Event,包含: 绑

JavaScript实现一个自定义事件函数Event,包含: 绑

作者: acsamson | 来源:发表于2019-05-26 16:34 被阅读0次
class Event {
  constructor() {
    // 为了查找迅速使用了对象
    this._cache = {};
  }
  // 绑定事件
  on(eventName, callback) {
    /* 为了查找方便和节省空间, 把同一类型事件放到数组中
     *  因为数组是有序的, 逻辑上是队列, 先绑定先触发
     * */
    // 如果有就放入, 没有就新建, 然后再看下是否有放入函数,没有就加入
    let fns = (this._cache[eventName] = this._cache[eventName] || []);
    // 如果事件方法没有的话就放入到字典进去
    if (fns.indexOf(callback === -1)) {
      fns.push(callback);
    }
    return this;
  }
  // 触发事件
  trigger(eventName, data) {
    // 看下字典里有没有这个函数名字, 有的话就触发它
    let fns = this._cache[eventName];
    if (Array.isArray(fns)) {
      // 有的话就对立面的每一个function传入参数data
      fns.forEach(fn => {
        fn(data);
      });
    }
    return this;
  }
  /*解绑, 看下字典里如果有这个事件名字就去
   * 看下要删除什么
   * */
  off(eventName, callback) {
    let fns = this._cache[eventName];
    if (Array.isArray(fns)) {
      if (callback) {
        let index = fns.indexOf(callback);
        if (index !== -1) {
          fns.splice(index, 1);
        }
      } else {
        // 全部清空
        fns.length = 0;
      }
    }
    return this;
  }
}
const event = new Event();
event.on("test", a => {
  console.log(a);
});
event.trigger("thet", "hello world"); // 绑定后就输出

event.off("test");
event.trigger("test", "hello world"); // 解绑后就不显示了

相关文章

网友评论

      本文标题:JavaScript实现一个自定义事件函数Event,包含: 绑

      本文链接:https://www.haomeiwen.com/subject/pqkftctx.html