removeEventListener 沒法解除匿名函數監聽問題

背景

removeEventListener 沒法移除匿名函數監聽node

解決方案

封裝原生 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
}
相關文章
相關標籤/搜索