提问人:blackened 提问时间:10/4/2022 最后编辑:blackened 更新时间:10/4/2022 访问量:42
JavaScript:实现事件删除器
JavaScript: Implementing Event Remover
问:
(JavaScript 的新手和闭包的想法。
我正在尝试实现 Wordle 克隆。在下面的代码片段中,我构造了屏幕上的键盘按钮并添加了事件侦听器。只是为每个按钮添加是微不足道的。但后来我了解到,就我而言,删除这些事件侦听器并不是那么容易。eventListener
我的问题是:如果我在循环内部定义,则无法访问它;如果我定义外部,那么我无法添加事件侦听器。const handleMouseClick = processMouseClick(key);
silenceKeyboard()
我应该怎么做才能调和两者?
function processMouseClick(e) {
return function closure() {
if (e === "DELETE") {
backspace();
document.activeElement.blur(); //important
return;
}
else if (e === "ENTER") {
processGuess();
document.activeElement.blur();
return;
}
else {
submitEnter(e);
document.activeElement.blur();
return;
}
}
}
function silenceKeyboard() {
const keyboard = document.getElementById("user-keyboard");
const buttons = keyboard.childNodes;
buttons.forEach(button => {
button.removeEventListener("click", handleMouseClick);
});
return;
}
function createKeyboard() {
const keys = [
"Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "A", "S", "D", "F", "G", "H", "J", "K", "L", "ENTER", "Z", "X", "C", "V", "B", "N", "M", "DELETE",
];
const keyboard = document.getElementById("user-keyboard");
keys.forEach((key) => {
const buttonElement = document.createElement("button");
buttonElement.textContent = key;
buttonElement.setAttribute("id", key);
keyboard.append(buttonElement);
const handleMouseClick = processMouseClick(key);
buttonElement.addEventListener("click", handleMouseClick);
});
return;
}
答:
0赞
Fabiano Taioli
10/4/2022
#1
只需进行最少的修改,您就可以执行以下操作
function silenceKeyboard() {
const keyboard = document.getElementById("user-keyboard");
const buttons = keyboard.childNodes;
buttons.forEach(button => {
button.removeEventListener("click", button._handleMouseClick);
});
return;
}
function createKeyboard() {
const keys = [
"Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "A", "S", "D", "F", "G", "H", "J", "K", "L", "ENTER", "Z", "X", "C", "V", "B", "N", "M", "DELETE",
];
const keyboard = document.getElementById("user-keyboard");
keys.forEach((key) => {
const buttonElement = document.createElement("button");
buttonElement.textContent = key;
buttonElement.setAttribute("id", key);
keyboard.append(buttonElement);
buttonElement._handleMouseClick = processMouseClick(key);
buttonElement.addEventListener(
"click",
buttonElement._handleMouseClick
);
});
return;
}
但是,可以更好地重构代码,以便为所有键提供单个事件侦听器。
评论
disable