javascript - 从窗口中删除所有侦听器
问题描述
我想在没有参考的情况下从窗口中删除游戏中的这些侦听器。怎么做?它可以被移除,分离,无论我想要什么。
actionListeners = () => {
window.addEventListener("keydown", (e) => {
if (e.key === "ArrowLeft") {
this.isArrowLeft = true;
} else if (e.key === "ArrowRight") {
this.isArrowRight = true;
}
});
window.addEventListener("keyup", (e) => {
if (e.key === " ") {
this.executeShot();
}
if (e.key === "Control") {
this.executeBarrier();
}
if (e.key === "ArrowLeft") {
this.isArrowLeft = false;
} else if (e.key === "ArrowRight") {
this.isArrowRight = false;
}
});
};
解决方案
如果每个事件只需要一个侦听器,则可以使用onkeydown
andonkeyup
和null
那些:
const actionListeners = () => {
window.onkeydown = (e) => {
if (e.key === "ArrowLeft") {
this.isArrowLeft = true;
} else if (e.key === "ArrowRight") {
this.isArrowRight = true;
}
});
window.onkeyup = (e) => {
if (e.key === " ") {
this.executeShot();
}
if (e.key === "Control") {
this.executeBarrier();
}
if (e.key === "ArrowLeft") {
this.isArrowLeft = false;
} else if (e.key === "ArrowRight") {
this.isArrowRight = false;
}
});
};
const removeListeners = () => {
window.onkeyup = window.onkeydown = null;
}
推荐阅读
- python - 向客户端发送字符串 - 接收 TypeError
- com - 虚拟机。捕获 COM 错误
- javascript - Mapbox GL JS - 删除图像叠加的淡入淡出
- arrays - 回显包含带有空格的元素的数组作为另一个命令的参数
- php - 如何通过从数据库中检索的查询值更改某些行的颜色
- javascript - 我想使用 JavaScript 将文本框保存到 HTML 中的 .txt 文件,但出现错误
- spring-boot - Flyway - 多个数据库上的数据迁移 - Spring Boot
- javascript - 使用javascript在codeigniter中设置会话
- wordpress - 我们可以有超过 2 个下划线的 wordpress 表名吗
- javascript - 使用onchange函数jquery传递varibel