从 addEventListener 中提取函数 [英] Extract function from addEventListener
问题描述
简而言之,我有 3 个 div,单击时它们的背景颜色会随机改变.它们只能被点击一次,因此 removeEventListener
.我只是想把事情复杂化吗?
In a nutshell, I have 3 divs that will have their bg colour randomly changed when clicked. They can only be clicked once, hence the removeEventListener
. Am I just trying to over-complicate things?
我有 3 个事件侦听器,它们都使用相同的函数,但每个都有自己的参数:
I have 3 event listeners that all use the same function, but each with its own arguments:
doorLeft.addEventListener("click", function handler(ev) {
randomChooseColour(doorLeft);
ev.currentTarget.removeEventListener(ev.type, handler);
});
doorMiddle.addEventListener("click", function handler(ev) {
randomChooseColour(doorMiddle);
ev.currentTarget.removeEventListener(ev.type, handler);
});
doorRight.addEventListener("click", function handler(ev) {
randomChooseColour(doorRight);
ev.currentTarget.removeEventListener(ev.type, handler);
});
randomChooseColour 是一个基本函数,它接受一个参数并改变 div 的背景颜色
randomChooseColour is a basic function that takes one argument and changes that div background colour
const randomChooseColour = (door) => {
if (randomSelect(2) === 0) {
door.style.backgroundColor = winColour;
} else {
door.style.backgroundColor = loseColour;
}
};
有没有办法在 addEventListener 之外创建该处理函数?我试图将它保存到一个常量,然后在 eventListener 中使用该常量,但它似乎不起作用
Is there any way to create that handler function outside the addEventListener? I tried to save it to a const and then use that const inside the eventListener, but it doesn't seem to work
const choose = function handler(ev, door) {
randomChooseColour(door);
ev.currentTarget.removeEventListener(ev.type, handler);
};
然后像这样使用它但是ev没有定义.
and then use it like this but ev is not defined.
doorLeft.addEventListener("click", choose(ev, doorLeft));
推荐答案
由于函数体的不同,我认为没有办法让 removeEventListener
可以在函数之外拥有一个单一的函数被要求.但是有一个简单的方法来简化事情:使用 { once: true }
这样监听器只能被调用一次,完全不需要 removeEventListener
.
Since the body of the functions are different, I don't think there's a way to have a singe outside function that removeEventListener
can be called for. But there is an easy way to simplify things: use { once: true }
so that the listener can only be called once, no need for removeEventListener
at all.
// the below line can be made less repetitive
// by using querySelectorAll instead, if possible
for (const door of [doorLeft, doorMiddle, doorRight]) {
door.addEventListener(
'click',
() => randomChooseColor(door),
{ once: true }
);
}
这篇关于从 addEventListener 中提取函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!