gpt4 book ai didi

javascript - 是否可以通过取消其回调函数来删除 EventListener?

转载 作者:行者123 更新时间:2023-11-28 19:45:24 25 4
gpt4 key购买 nike

我想知道是否可以通过取消其回调函数来删除事件监听器?

简化示例:

var somefunction = function() {
// some code
}
window.addEventListener(eventType, somefunction, false);

现在,设置 somefunction = null; 会删除上述 EventListener,还是会简单地将其变成僵尸 EventListener?

实际代码在 Firefox(覆盖类型)插件中使用,我正在考虑(自动)删除 unload 事件上的 EventListener 的替代方法,除了明显的方法之外:

window.removeEventListener(eventType, somefunction, false); 

更新:请注意,这是 Firefox 插件代码的一部分。此实例中的 eventType 为 'popupshowing',它不能被取消,因为它会破坏浏览器功能。

预先感谢您的帮助期待(替代)建议

最佳答案

removeEventListener 是正确的方法。

此外,您实际上并没有通过将某些变量设置为 null 来使函数无效。该变量仅分配了一个引用(对非 POD 对象,如函数)。为了说明这一点,请考虑以下内容:

var a = function() { alert("called"); };
setTimeout(a, 1000); // Will still alert!

var b = a;

a = null; // What you called `nullify`....
console.log(this.a, "a" in this); // null, true
delete this.a; // Actually remove the property from the global scope.
// `a` is really dead at this point!

b(); // will still alert, too.

如果您想避免一些 removeEventListener 调用,我会使用一些辅助函数:

let { addEventListenerUnload, removeEventListenerUnload } = (function() {
let tracked = [];
addEventListener("unload", function removeTracked() {
removeEventListener("unload", removeTracked);
for (let t of tracked) {
try {
removeEventListener(t.type, t.fn, t.capture);
}
catch (ex) {}
}
tracked.length = 0;
});
return {
addEventListenerUnload: function(type, fn, capture) {
addEventListener(type, fn, capture);
tracked.push({type: type, fn: fn, capture: capture});
},
removeEventListenerUnload: function(type, fn, capture) {
tracked = tracked.filter(e => e.type != type || e.fn != fn || e.capture != capture);
removeEventListener(type, fn, capture);
}
};
})();

(包括 Firefox 支持的一些 ECMA-6 内容,但您可以轻松转换它们。此外,可能根本不需要 removeEventListenerUnload,因此您可能会忽略它。另外,当在覆盖脚本请确保为其指定唯一的名称,以避免与其他代码发生冲突)。

关于javascript - 是否可以通过取消其回调函数来删除 EventListener?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24363471/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com