2

我希望能夠處理鍵盤事件,但也能夠停止/開始處理它們,因爲我希望在我的代碼中。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); 
    } 

} 

回答

2

一起工作後,我們推出了這個解決方案:

var keypress = require('keypress'); 

declare var process: any; 

class Game { 

    private gameOver: boolean = false; 
    private timeOfRoundMillis: number = 5 * 1000; 
    private capturedInput: string[]; 

    constructor() { 
    keypress(process.stdin); 

    process.openStdin().on('keypress', (key) => { 
     // I want to call this every time a key is pressed 
     this.capturedInput.push(key); 
    }); 
    process.stdin.setRawMode(true); 
    } 

    public play(): void { 
    this.round(); 
    } 

    private round(): void { 

    if (!this.gameOver) { 

     setTimeout(() => { 
     // Now I want to stop capturing keys to process the input 
     this.isCapturingKeys = false; // need to set it to true when you desire to start capturing again 
     this.processPlayerInput(); 
     this.emptyCapturedInput(); 
     this.round(); 
     }, this.timeOfRoundMillis); 

    } else { 
     process.stdin.pause(); // close stdin events 
    } 

    } 

    private processPlayerInput(): void { 
     // do some stuff with 'capturedInput' 
    } 
} 
+0

這看起來不錯,但我使用Node.j打字稿所以'窗口'不存在。 – charliebrownie

+0

確定使用'process.openStdin()'代替。 – artemisian

+0

非常感謝,你讓我的一天,它完美的作品! :-) – charliebrownie