解決removeEventListener 無法清除監(jiān)聽的問題
1. 原因
許多入前端不久的人都會遇到 removeEventListener 無法清除監(jiān)聽的情況,這是由于
要移除事件句柄,addEventListener() 的執(zhí)行函數(shù)必須使用外部函數(shù),如上實例所示 (myFunction)。
匿名函數(shù),類似 “document.removeEventListener(“event”, function(){ myScript });” 該事件是無法移除的。
而在很多情況下我們需要句柄回調(diào)的傳參,又需要其他傳參時免不了使用句柄,這個時候我們需要寫一個方法去替代這個回調(diào),以下是解決方式,寫了一個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;
補充知識:vue 創(chuàng)建監(jiān)聽,和銷毀監(jiān)聽(addEventListener, removeEventListener)
最近在做一個有關(guān)監(jiān)聽scroll的功能, 發(fā)現(xiàn)我添加監(jiān)聽之后一直不起作用:
mounted() {
window.addEventListener("scroll", this.setHeadPosition); //this.setHeadPosition方法名
后來發(fā)現(xiàn)要在后面添加一個true之后才行:
mounted() {
window.addEventListener("scroll", this.setHeadPosition, true);
},
而在離開是的時候需要銷毀監(jiān)聽: (在destroyed里面銷毀), 否則監(jiān)聽會一直存在, 因為這是單頁面應(yīng)用, 頁面并未關(guān)閉.
destroyed() {
window.removeEventListener("scroll", this.setHeadPosition, true);
},
在銷毀的時候一定也要加上true, 否則銷毀不起作用.
以上這篇解決removeEventListener 無法清除監(jiān)聽的問題就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue.js數(shù)據(jù)加載完成前顯示原代碼{{代碼}}問題及解決
這篇文章主要介紹了vue.js數(shù)據(jù)加載完成前顯示原代碼{{代碼}}問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-07-07
vant-list組件觸發(fā)多次onload事件導(dǎo)致數(shù)據(jù)亂序的解決方案
這篇文章主要介紹了vant-list組件觸發(fā)多次onload事件導(dǎo)致數(shù)據(jù)亂序的解決方案2023-01-01
vue前端如何接收后端傳過來的帶list集合的數(shù)據(jù)
這篇文章主要介紹了vue前端如何接收后端傳過來的帶list集合的數(shù)據(jù),前后端交互,文中的示例Json報文,前端采用vue進行接收,本文結(jié)合實例代碼給大家介紹的非常詳細,感興趣的朋友一起看看吧2024-02-02

