From 3599c362036f957384f8e62fde6872937fc2c582 Mon Sep 17 00:00:00 2001 From: Gamaliel Garcia <46827955+EGAMAGZ@users.noreply.github.com> Date: Sat, 20 Apr 2024 16:31:11 -0600 Subject: [PATCH] fix(paska-ovo): Remove and add event listener when a key listener already exists --- src/paska-ovo.ts | 37 +++++++++++++++++++++++++++++-------- 1 file changed, 29 insertions(+), 8 deletions(-) diff --git a/src/paska-ovo.ts b/src/paska-ovo.ts index 4fc1865..5de1237 100644 --- a/src/paska-ovo.ts +++ b/src/paska-ovo.ts @@ -16,6 +16,7 @@ export class PaskaOvo { private keysPressed: string[] = []; + private keyListener?: ((event: KeyboardEvent) => void); /** * Constructs a new instance of the class with optional parameters for an easter egg. @@ -71,6 +72,18 @@ export class PaskaOvo { }); } + /** + * Creates a function that handles the key event. + * + * @param {EasterEgg[]} easterEggs - List of easter eggs to trigger. + * @return {(event: KeyboardEvent) => void} Function that handles the key event. + */ + private createHandleKeyEvent(easterEggs: EasterEgg[]): (event: KeyboardEvent) => void { + return (event: KeyboardEvent) => { + this.handleKeyEvent(event, easterEggs); + } + } + /** * Resets the keysPressed array to an empty array. */ @@ -90,17 +103,25 @@ export class PaskaOvo { return this; } - private stop() { - // document.addEventListener() + /** + * Adds an event listener to the document for keyup events if it is not already added. + */ + public listen() { + if (this.keyListener !== undefined) { + this.stop(); + } + this.keyListener = this.createHandleKeyEvent(this.easterEggs); + + document.addEventListener("keyup", this.keyListener); } /** - * Adds an event listener to the document for keyup events. - */ - public listen() { - document.addEventListener("keyup", (event) => { - this.handleKeyEvent(event, this.easterEggs) - }, false); + * Removes the event listener from the document. + * */ + public stop() { + if (this.keyListener) { + document.removeEventListener("keyup", this.keyListener); + } } }