-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKeyPressListener.js
More file actions
39 lines (32 loc) · 1.39 KB
/
KeyPressListener.js
File metadata and controls
39 lines (32 loc) · 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// to listen for keypresses, to be used in multiple situations
// replicates a default button - press down, something happens, must release + repress to fire again
// adding listener for KeyDown would just rapid fire when key is held down, which is not cool
class KeyPressListener {
constructor(keyCode, callback) { // callback is what will happen when the keycode is pressed down once
let keySafe = true;
this.keydownFunction = function(event) {
if (event.code === keyCode) {
if (keySafe) {
keySafe = false;
callback();
}
}
};
this.keyupFunction = function(event) {
if (event.code === keyCode) {
keySafe = true;
}
};
document.addEventListener("keydown", this.keydownFunction);
document.addEventListener("keyup", this.keyupFunction);
// when the document hears a keydown press that matches the keyCode,
// itll fire the callback ONLY ONCE until the keyup is fired
// then after the dialogue or whatever finishes, unbind the event listener,
// so that the document no longer looks for that "enter" keypress
}
// unbinding
unbind() {
document.removeEventListener("keydown", this.keydownFunction);
document.removeEventListener("keyup", this.keyupFunction);
}
}