欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

解決removeEventListener 無法清除監(jiān)聽的問題

 更新時(shí)間:2020年10月30日 10:56:27   作者:甩頭淡忘煩惱  
這篇文章主要介紹了解決removeEventListener 無法清除監(jiān)聽的問題,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧

1. 原因

許多入前端不久的人都會(huì)遇到 removeEventListener 無法清除監(jiān)聽的情況,這是由于

要移除事件句柄,addEventListener() 的執(zhí)行函數(shù)必須使用外部函數(shù),如上實(shí)例所示 (myFunction)。

匿名函數(shù),類似 “document.removeEventListener(“event”, function(){ myScript });” 該事件是無法移除的。

而在很多情況下我們需要句柄回調(diào)的傳參,又需要其他傳參時(shí)免不了使用句柄,這個(gè)時(shí)候我們需要寫一個(gè)方法去替代這個(gè)回調(diào),以下是解決方式,寫了一個(gè)addListener 函數(shù)在 addEventListener 之后返回它的銷毀方法

2.解決方式

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('缺少參數(shù)');
 }
 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;

補(bǔ)充知識(shí):vue 創(chuàng)建監(jiān)聽,和銷毀監(jiān)聽(addEventListener, removeEventListener)

最近在做一個(gè)有關(guān)監(jiān)聽scroll的功能, 發(fā)現(xiàn)我添加監(jiān)聽之后一直不起作用:

mounted() {

window.addEventListener("scroll", this.setHeadPosition); //this.setHeadPosition方法名

后來發(fā)現(xiàn)要在后面添加一個(gè)true之后才行:

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

而在離開是的時(shí)候需要銷毀監(jiān)聽: (在destroyed里面銷毀), 否則監(jiān)聽會(huì)一直存在, 因?yàn)檫@是單頁面應(yīng)用, 頁面并未關(guān)閉.

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

在銷毀的時(shí)候一定也要加上true, 否則銷毀不起作用.

以上這篇解決removeEventListener 無法清除監(jiān)聽的問題就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論