From 7fe84972cce8717ac13f3ba199f6ca7621e9c8c2 Mon Sep 17 00:00:00 2001 From: weiseng18 Date: Wed, 2 Sep 2020 20:24:14 +0800 Subject: [PATCH] [code] created a toggleKeyPressListener to toggle the key press listener for keybindings --- js/start_menu.js | 2 +- js/tools.js | 15 +++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/js/start_menu.js b/js/start_menu.js index 6efe0ec..a793a8b 100644 --- a/js/start_menu.js +++ b/js/start_menu.js @@ -176,5 +176,5 @@ StartMenu.prototype.closeMenu = function(which) { document.body.removeChild(this.ele); // add keypress listener - document.addEventListener("keypress", tools.keyPressListener.bind(tools)); + tools.toggleKeyPressListener(); } \ No newline at end of file diff --git a/js/tools.js b/js/tools.js index 7d33f68..7119c58 100644 --- a/js/tools.js +++ b/js/tools.js @@ -22,6 +22,10 @@ function ToolWrapper(rows, columns) { // currently, keybinds will be a single letter only this.keybinds = ["Q", "W", "E", "R", "T", "Y", "A", "S", "D", "F", "G", "H"]; + this.enabledKeyPress = false; + + // binded key press listener + this.bindedKeyPressListener = this.keyPressListener.bind(this); } ToolWrapper.prototype.addTool = function(tool) { @@ -75,6 +79,17 @@ ToolWrapper.prototype.generateHTML = function() { get(this.wrapperID).appendChild(table); } +ToolWrapper.prototype.toggleKeyPressListener = function() { + if (this.enabledKeyPress) { + document.removeEventListener("keypress", this.bindedKeyPressListener); + this.enabledKeyPress = false; + } + else { + document.addEventListener("keypress", this.bindedKeyPressListener); + this.enabledKeyPress = true; + } +} + ToolWrapper.prototype.keyPressListener = function(e) { var key = e.which || e.keyCode;