gpt4 book ai didi

javascript - 通过 addEventListener 添加的事件监听器被多次调用

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

我正在使用 addEventListener 对某些事件使用react。

据我了解,可以在同一个EventTarget上注册多个相同的EventListener,并且EventListener只会被调用一次。

以下是来自 MDN 的引用:

If multiple identical EventListeners are registered on the same EventTarget with the same parameters, the duplicate instances are discarded. They do not cause the EventListener to be called twice, and they do not need to be removed manually with the removeEventListener() method. Note however that when using an anonymous function as the handler, such listeners will NOT be identical since anonymous functions are not identical even if defined using the SAME unchanging source-code simply called repeatedly, even if in a loop. However, repeatedly defining the same named function in such cases can be more problematic. (see Memory issues below.)

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Multiple_identical_event_listeners

我不确定为什么在这个例子中没有发生这种情况?运行此代码将调用 EventListener 两次:(Codepen here )

function _callback() { console.log("fnFunction"); }

function init() {
attachGesture("panel-anchor", _callback);
attachGesture("panel-anchor", _callback);
}

function attachGesture(sElementId, fnFunction) {
var oElement = document.getElementById(sElementId);

function foo() {
console.log("Foo");
fnFunction();
}

oElement.addEventListener("click", foo, false);
}

window.onload = init;

如何确保 EventListener 仅被调用一次?

最佳答案

it is possible to register multiple identical EventListeners on the same EventTarget, and the EventListener will only be called once.

事实并非如此。

如果您多次注册相同事件处理程序,那么它只会被调用一次。

相同但不相同的===事件处理程序不是相同事件处理程序。

您需要更改逻辑以避免尝试注册相同的处理程序。

关于javascript - 通过 addEventListener 添加的事件监听器被多次调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53593351/

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