我希望能夠處理鍵盤事件,但也能夠停止/開始處理它們,因爲我希望在我的代碼中。Typescript:創建KeyboardEvent並在任何時候激活/停用
我一直在讀通過MDN Mozilla Docs有關KeyboardEvent
,它從Event
繼承的方式,我看到我能夠使用一些有用的方法是什麼我想實現如:
event.initEvent
event.preventDefault
但是經過一番研究,並試圖把東西放在一起,我掙扎,無法最終找到做它的方式。
只是爲了證明我一直試圖弄清楚如何和我的解決方案的工作,我想告訴你什麼是我到目前爲止有:
class Game {
private gameOver: boolean = false;
private timeOfRoundMillis: number = 5 * 1000;
private keyboardEvent: KeyboardEvent;
private capturedInput: string[];
constructor() {}
public play(): void {
this.round();
}
private round(): void {
if (!this.gameOver) {
// I want to start capturing keys
keyboardEvent.initEvent();
setTimeout(() => {
// Now I want to stop capturing keys to process the input
keyboardEvent.preventDefault();
this.processPlayerInput();
this.emptyCapturedInput();
this.round();
}, this.timeOfRoundMillis);
}
}
private processPlayerInput(): void {
// do some stuff with 'capturedInput'
}
// I want to call this every time a key is pressed if
// capturing keyboard events is active
private capture(e): void {
capturedInput.push(e.keyPressed);
}
}
這看起來不錯,但我使用Node.j打字稿所以'窗口'不存在。 – charliebrownie
確定使用'process.openStdin()'代替。 – artemisian
非常感謝,你讓我的一天,它完美的作品! :-) – charliebrownie