关于javascript:removeEventListener-无法解除匿名函数监听问题

12次阅读

共计 998 个字符,预计需要花费 3 分钟才能阅读完成。

背景

removeEventListener 无奈移除匿名函数监听

解决方案

封装原生 addEventListener, 暴露出移除事件监听的办法

代码

function isFn(value) {const type = Object.prototype.toString.call(value);
  return type === '[object Function]';
}
function isNode(value) {return value !== undefined && value instanceof HTMLElement && value.nodeType === 1;}

function listenNode(node, type, callback) {node.addEventListener(type, callback);
  return {destroy() {node.removeEventListener(type, callback);
    },
  };
}

function addListener(target, type, callback) {if (!target && !type && !callback) {throw new Error('短少参数');
  }
  if (!isFn(callback)) {throw new TypeError('Third argument must be a Function');
  }
  if (isNode(target)) {return listenNode(target, type, callback);
  }
  throw new TypeError('First argument must be a String, HTMLElement, HTMLCollection, or NodeList');
}

function listenNodeList(nodeList, type, callback) {
  Array.prototype.forEach.call(nodeList, node => {node.addEventListener(type, callback);
  });

  return {destroy() {
      Array.prototype.forEach.call(nodeList, node => {node.removeEventListener(type, callback);
      });
    },
  };
}

export default {
listenNode,
listenNodeList
}

正文完
 0