我希望能够处理键盘事件,但是也可以根据我希望在代码中再次停止/开始处理它们。

我一直在阅读有关KeyboardEventMDN Mozilla Docs以及它从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);
      }
    
    }
    

    最佳答案

    共同努力之后,我们提出了以下解决方案:

    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'
      }
    }
    

    关于javascript - typescript :创建KeyboardEvent并随时激活/停用它,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42704840/

    10-09 01:54