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

时间:2019-04-26 04:38:50

标签: javascript

我想停止事件侦听器,直到单击“甜蜜警报”的“确定”按钮为止。在我的代码中,当弹出甜蜜警报时,其中带有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 .

1 个答案:

答案 0 :(得分:0)

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

document.addEventListener('keyup', eventListenerCallback);

然后,当您的甜蜜警报在respawn内部触发时,您可以删除侦听器:

document.removeEventListener('keyup', eventListenerCallback);