جاوااسکریپت - تایپاسکریپت: ایجاد KeyboardEvent و فعال/غیرفعال کردن آن در هر زمان


من دوست دارم توانایی مدیریت رویدادهای صفحهکلید را داشته باشم، اما همچنین قادر باشم مدیریت آنها را دوباره متوقف یا شروع کنم هر زمان که بخواهم در داخل کد خود.

من در حال مطالعه مستندات MDN موزیلا درباره 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'
  }
}

پاسخ شماره ۲

شاید رویداد "isComposing" باشد (boolean، درست اگر در حال تایپ باشد) فونت: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent