Resolve the problem that removeEventListener cannot clear listening

  • 2021-09-11 19:26:11
  • OfStack

1. Reasons

Many people who have been in the front end for a long time will encounter the situation that removeEventListener can't clear the listening, because

To remove the event handle, the execution function of addEventListener () must use an external function, as shown in the above example (myFunction).

Anonymous function, similar to "document. removeEventListener (" event ", function () {myScript});" This event cannot be removed.

In many cases, we need to pass the parameter of the handle callback, and we need to use the handle when we need other parameters. At this time, we need to write a method to replace this callback. The following is the solution. Write an addListener function to return its destruction method after addEventListener

2. Solutions


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(' Missing parameter ');
 }
 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);
   });
  },
 };
}
module.exports = listener;

Additional knowledge: vue create listeners, and destroy listeners (addEventListener, removeEventListener)

Recently, I was doing a function about monitoring scroll, and found that after I added monitoring, 1 didn't work directly:

mounted() {

window. addEventListener ("scroll", this. setHeadPosition); //this. setHeadPosition method name

Later, it was found that it was necessary to add an true after:


mounted() {
 window.addEventListener("scroll", this.setHeadPosition, true);
},

When you leave, you need to destroy the monitor: (destroy it in destroyed), otherwise the monitor will exist directly, because this is a single-page application and the page is not closed.


destroyed() {
 window.removeEventListener("scroll", this.setHeadPosition, true);
},

true must also be added at the time of destruction, otherwise the destruction will not work.


Related articles: