解決removeEventListener 無法清除監(jiān)聽的問題
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)文章
vue.js數(shù)據(jù)加載完成前顯示原代碼{{代碼}}問題及解決
這篇文章主要介紹了vue.js數(shù)據(jù)加載完成前顯示原代碼{{代碼}}問題及解決方案,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-07-07vant-list組件觸發(fā)多次onload事件導(dǎo)致數(shù)據(jù)亂序的解決方案
這篇文章主要介紹了vant-list組件觸發(fā)多次onload事件導(dǎo)致數(shù)據(jù)亂序的解決方案2023-01-01vue項(xiàng)目打包之后在本地運(yùn)行的實(shí)現(xiàn)方法
這篇文章主要介紹了vue項(xiàng)目打包之后在本地運(yùn)行的實(shí)現(xiàn)方法,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-07-07vue前端如何接收后端傳過來的帶list集合的數(shù)據(jù)
這篇文章主要介紹了vue前端如何接收后端傳過來的帶list集合的數(shù)據(jù),前后端交互,文中的示例Json報(bào)文,前端采用vue進(jìn)行接收,本文結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),感興趣的朋友一起看看吧2024-02-02