javascript - Typescript:创建 KeyboardEvent 并随时激活/停用它

标签 javascript typescript event-handling dom-events keyboard-events

我希望能够处理键盘事件,但也能够在我的代码中按照我的意愿再次停止/开始处理它们。

我一直在阅读 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);
  }

}

最佳答案

经过共同努力,我们得出了这个解决方案:

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/

相关文章:

javascript - 更改引导导航栏中的事件类不保留在继承的 Django 模板中

typescript - moment.js 如何用 typescript 导入?

typescript - 如何阻止 typescript 编译器因为我的变量不是驼峰式命名而中止?

c# - 将 CheckChanged 事件处理程序添加到动态添加的 UserControl 中的 CheckBox

event-handling - 如何在不实例化事件中每个实例的情况下处理子类 View 事件?

javascript - 使用 CSS 将子菜单定位到主菜单的右侧

javascript - 用六边形填充圆(不同的方法)

javascript - NodeJS 中奇怪的 express.use() 行为

javascript - 如何通过使用 moment 减去两个日期来获得总小时数?

java - 我的鼠标处理程序类导致鼠标移动和结果之间呈几何级数,我正在寻找原因