-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKeyPressListener.js
More file actions
31 lines (28 loc) · 875 Bytes
/
KeyPressListener.js
File metadata and controls
31 lines (28 loc) · 875 Bytes
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
class KeyPressListener {
constructor(keyCode, callback) {
// once callback is called this will be false and then callback won't run again until this is true
let keySafe = true;
// listens for the key to be pressed down
this.keydownFunction = function (event) {
if (event.code === keyCode) {
if (keySafe) {
keySafe = false;
callback();
}
}
};
// listens for the key to be unpressed
this.keyupFunction = function (event) {
if (event.code === keyCode) {
keySafe = true;
}
};
document.addEventListener("keydown", this.keydownFunction);
document.addEventListener("keyup", this.keyupFunction);
}
// stops listening
unbind() {
document.removeEventListener("keydown", this.keydownFunction);
document.removeEventListener("keyup", this.keyupFunction);
}
}