首页 > 解决方案 > 从窗口中删除所有侦听器

问题描述

我想在没有参考的情况下从窗口中删除游戏中的这些侦听器。怎么做?它可以被移除,分离,无论我想要什么。

 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;
        }
    });
};

标签: javascriptremoveeventlistener

解决方案


如果每个事件只需要一个侦听器,则可以使用onkeydownandonkeyupnull那些:

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;
}

推荐阅读