如何停止事件监听器直到我在甜蜜警报消息上单击“确定”?

问题描述 投票:0回答:1

我想暂停我的事件监听器,直到我点击甜蜜警报的确定按钮。在我的代码中,甜蜜警报弹出game overok按钮。我想确保暂停我的事件监听器,直到我点击弹出窗口中的ok按钮。现在我的游戏可以在我甜蜜警报弹出的背景下播放,我不想这样做。这是我的代码。

document.addEventListener('keyup', function (e) {
    console.log('hi')
    var allowedKeys = {
        37: 'left',
        38: 'up',
        39: 'right',
        40: 'down'
    };

    player.handleInput(allowedKeys[e.keyCode]);
});

class Player {

    static lifeCount = 3;

    constructor(x, y) {
        this.x = x;
        this.y = y;
        this.sprite = 'images/char-boy.png';

    }

    handleInput(key) {
        if (key === 'left' && this.x > 4) {
            this.x -= 100;
        }
        if (key === 'right' && this.x < 400) {
            this.x += 100;
        }
        if (key === 'up' && this.y > -20) {
            this.y -= 85;
        }
        if (key === 'down' && this.y < 400) {
            this.y += 85;
        }
    }

    update() {
        if (this.y === -25) {
            console.log('this is win')
            this.x = 200;
            this.y = 400;
            swal({
                title: "Good job!",
                text: "You won this level",
                icon: "success",
                button: "Play next!",
            });
            levelCount++;
            level.innerHTML = `Level - ${levelCount}`;
        }
    }

    render() {
        ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
    }

    respawn() {
        swal({
            title: "Try again!",
            text: "bugs are deadly",
            icon: "error",
            button: "Play again!",
        });
        this.x = 200;
        this.y = 400;

        if (Player.lifeCount < 1) {
            levelCount = 1;
        }

        Player.lifeCount--;
        if (Player.lifeCount < 3) {
            img.removeChild(img.firstElementChild);
        }
    }
}
player.respawn(); // here when sweet alert get executed I wanted to halt my 
                 //event listener operation till I click Ok button in sweet 
                 //alert .
javascript
1个回答
0
投票

也许您可以在执行甜蜜警报时删除事件侦听器,然后在警报关闭后,您可以添加侦听器。你需要将addEventListener的回调函数重构为它自己的函数,然后将它传递给你的eventListener。像这样的东西:

document.addEventListener('keyup', eventListenerCallback);

然后当你的甜蜜警报在respawn内部发射时,你可以移除听众:

document.removeEventListener('keyup', eventListenerCallback);

© www.soinside.com 2019 - 2024. All rights reserved.