如何让JavaScript类在继续之前等待特定的键被按下?

ozxc1zmp  于 2023-06-04  发布在  Java
关注(0)|答案(1)|浏览(105)

我尝试做的是等待,直到正确的键被按下,让它继续
到目前为止我做的代码是这样的:

class exampleClass {
    async waitForKeyPress() {
        return new Promise((resolve) => {
        
            const listener = (e) => {
                document.body.removeEventListener("keydown", listener);
                if(e.key == "z") {resolve(); alert("e");}
                else {
                    this.waitForKeyPress();
                }
            }
            document.body.addEventListener("keydown", listener);
        });
    }

    async doStuff() {
        await this.waitForKeyPress();
        console.log("correct key pressed");
        //do stuff
    }
}

let exampleObject = new exampleClass();
exampleObject.doStuff();

这对我不起作用,因为如果我按下不同的键,它不会检测到z键因某种原因被按下。

async function waitForKeyPress() {
        return new Promise((resolve) => {
        
            const listener = (e) => {
                document.body.removeEventListener("keydown", listener);
                if(e.key == "z") resolve();
                else {
                    this.waitForKeyPress();
                }
            }
            document.body.addEventListener("keydown", listener);
        });
    }

    async function doStuff() {
        await this.waitForKeyPress();
        console.log("correct key pressed");
        //do stuff
    }

    doStuff();

唯一的区别是它不在课堂上。不过,我希望它是在一个类

pftdvrlh

pftdvrlh1#

仅在按下z时删除侦听器,而不是过早删除它。

class exampleClass {
    async waitForKeyPress() {
        return new Promise((resolve) => {
            const listener = (e) => {
                if(e.key === "z") {
                    window.removeEventListener("keydown", listener);
                    resolve();
                }
            }
            window.addEventListener("keydown", listener);
        });
    }

    async doStuff() {
        await this.waitForKeyPress();
        console.log("correct key pressed");
        //do stuff
    }
}

let exampleObject = new exampleClass();
exampleObject.doStuff();

没有承诺

class exampleClass {
    constructor() {
        // the reason for this line is because "this"
        // inside doStuff will be window instead of
        // the class itself.
        this.doStuff = this.doStuff.bind(this)
        window.addEventListener("keydown", this.doStuff);
    }
    
    doStuff(e) {
        if(e.key !== 'z') return
        window.removeEventListener("keydown", this.doStuff)
        console.log("correct key pressed");
        //do stuff
    }
}

let exampleObject = new exampleClass();

相关问题