如何使一个JavaScript类在继续之前等待特定按键被按下?

huangapple go评论76阅读模式
英文:

How can I make a JavaScript class wait for a specific key to be pressed before continuing?

问题

我试图做的是等待正确的按键被按下后才继续执行。

我迄今为止编写的代码如下:

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");
        // 做一些事情
    }
}

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");
    // 做一些事情
}

doStuff();

它可以工作,唯一的区别是它不在一个类中。但是,我希望它在一个类中。

英文:

What I'm trying to do is to wait until the correct key is pressed for it to continue

The code i've done so far is this:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

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

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

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

<!-- end snippet -->
This doesn't work for me since if I press a different key then it doesn't detect that the z key is pressed for some reason
The part that is confusing for me is is that if you do

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

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

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

    doStuff();

<!-- end snippet -->

it works, the only difference is that it's not in a class. However, I would like it to be in a class

答案1

得分: 2

以下是翻译好的部分:

只有在按下“z”键时才删除监听器,而不是过早地删除它。

使用Promise的情况下:

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("正确的键被按下");
        //执行其他操作
    }
}

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

没有使用Promise的情况下:

class exampleClass {
constructor() {
// 这行的原因是因为在doStuff内部,“this”将是window而不是类本身。
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("正确的键被按下");
    //执行其他操作
}

}

let exampleObject = new exampleClass();


<details>
<summary>英文:</summary>

Remove listener only when `z` is pressed instead of removing it prematurely.

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(&quot;correct key pressed&quot;);
    //do stuff
}

}

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


Without promise,

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 !== &#39;z&#39;) return
    window.removeEventListener(&quot;keydown&quot;, this.doStuff)
    console.log(&quot;correct key pressed&quot;);
    //do stuff
}

}

let exampleObject = new exampleClass();


</details>



huangapple
  • 本文由 发表于 2023年6月2日 10:15:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76386742.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定