add class for keyboard events

This commit is contained in:
lagaffe 2026-04-19 13:26:59 +02:00
parent 5057de5572
commit 0a95900c55
2 changed files with 47 additions and 0 deletions

View file

@ -1,3 +1,4 @@
export { backgroundLayout } from "./layouts"; export { backgroundLayout } from "./layouts";
export { makeDragable, makeUnDragable } from "./dragAndDrop"; export { makeDragable, makeUnDragable } from "./dragAndDrop";
export { getIntersection } from "./helpers"; export { getIntersection } from "./helpers";
export { KeyBoardListener } from "./keyBoardEvents";

View file

@ -0,0 +1,46 @@
export class KeyBoardListener {
static _listenersKeyUp = {};
static _listenersKeyDown = {};
static ready = false;
static _listenCount = 0;
static init() {
document.addEventListener("keydown", (event) => {
for (const listener of Object.values(
KeyBoardListener._listenersKeyDown,
)) {
listener(event);
}
});
document.addEventListener("keyup", (event) => {
for (const listener of Object.values(
KeyBoardListener._listenersKeyUp,
)) {
listener(event);
}
});
KeyBoardListener.ready = true;
}
/* return id used to remove the listener */
static onKeyDown(callback) {
const id = KeyBoardListener._listenCount++;
KeyBoardListener._listenersKeyDown[id] = callback;
return id;
}
static offKeyDown(id) {
delete KeyBoardListener._listenersKeyDown[id];
}
/* return id used to remove the listener */
static onKeyUp(callback) {
const id = KeyBoardListener._listenCount++;
KeyBoardListener._listenersKeyUp[id] = callback;
return id;
}
static offKeyUp(id) {
delete KeyBoardListener._listenersKeyUp[id];
}
}