首页 > 解决方案 > 如何停止事件侦听器,直到我在甜蜜警报消息上单击确定?

问题描述

我想停止我的事件监听器,直到我点击甜蜜警报的确定按钮。在我的代码中,当弹出甜蜜警报时,其中包含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

解决方案


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

document.addEventListener('keyup', eventListenerCallback);

然后当你内心的甜蜜警报触发时,respawn你可以移除监听器:

document.removeEventListener('keyup', eventListenerCallback);


推荐阅读