如何阻止此文档附加事件侦听器发出重复事件?

How can I stop this document attached event listener from emitting duplicate events?

我希望游戏在按键时触发事件,但是当我导航离开和返回游戏页面时,事件侦听器触发两次。我发现了另一个问题,建议我在添加之前删除监听器,但这没有帮助。

侦听器是在 mounted

期间添加的
mounted() {
        this.setupInputListener();
    },

并且 keydown 事件侦听器被添加到文档中

        keydownListener() {
            const action = handleKeyDown(event.key);
            if ( action ) {
                this.SEND_INPUT({
                    gameId: this.gameId,
                    action: action
                });
            }
        },
        setupInputListener() {
            document.removeEventListener('keydown', this.keydownListener);
            document.addEventListener('keydown', this.keydownListener);
        }

如何防止此 keydown 侦听器发出重复事件?

您不能多次添加一个事件侦听器,这会导致它触发一次或多次。为避免这种情况,请尝试使用 onkeydown。一旦我们这样做,我们就不再需要 removeEventListener。例如,像这样的东西应该可以工作:

keydownListener() {
        const action = handleKeyDown(event.key);
        if (action) {
            this.SEND_INPUT({
                gameId: this.gameId,
                action: action
            });
        }
    },
    setupInputListener() {
        document.onkeydown = () => {
            this.keydownListener;
        }
    }

希望对您有所帮助!