javascript - Typescript: יצירת KeyboardEvent והפעלתו/השבתתו בכל זמן
אני רוצה להיות מסוגל לטפל באירועי מקלדת, אך גם להיות מסוגל להפסיק/להתחיל לטפל בהם שוב לפי רצוני בתוך הקוד שלי.
קראתי את מסמכי MDN של מוזילה על KeyboardEvent, ובדרך שבה הוא יורש מ-Event אני רואה שאני יכול להשתמש בכמה שיטות שימושיות למה שאני רוצה להשיג כמו:
event.initEventevent.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);
}
}
תשובה #1
לאחר שעבדנו יחד הגענו לפתרון הזה:
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'
}
}
תשובה #2
אולי האירוע הוא "isComposing" (בוליאני, נכון אם הוא מורכב) גופן: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent
