-1

I want to remove this listeners at the and of the game from window without reference. How to do that? It can be removed, detached, whatever just I want to be them off.

 actionListeners = () => {
    window.addEventListener("keydown", (e) => {
        if (e.key === "ArrowLeft") {
            this.isArrowLeft = true;
        } else if (e.key === "ArrowRight") {
            this.isArrowRight = true;
        }
    });

    window.addEventListener("keyup", (e) => {
        if (e.key === " ") {
            this.executeShot();
        }

        if (e.key === "Control") {
            this.executeBarrier();
        }

        if (e.key === "ArrowLeft") {
            this.isArrowLeft = false;
        } else if (e.key === "ArrowRight") {
            this.isArrowRight = false;
        }
    });
};
connexo
  • 53,704
  • 14
  • 91
  • 128
wnq
  • 25
  • 6
  • Does this answer your question? [How to remove all listeners in an element?](https://stackoverflow.com/questions/9251837/how-to-remove-all-listeners-in-an-element) – Manas Khandelwal Apr 11 '21 at 08:22
  • @ManasKhandelwal `window` is not an element. There is no way to remove event listeners from `window` or `document` unless you have a reference to the listener. The only thing you can do is reload the page, or destroy the current document using `document.write` while the stream is already closed. – connexo Apr 11 '21 at 08:25
  • Is your question answered? If yes, please pick the best answer. If not, please comment accordingly. – connexo Apr 12 '21 at 11:09

1 Answers1

0

If you need only one listener per event, you can work with onkeydown and onkeyup and null those:

const actionListeners = () => {
    window.onkeydown = (e) => {
        if (e.key === "ArrowLeft") {
            this.isArrowLeft = true;
        } else if (e.key === "ArrowRight") {
            this.isArrowRight = true;
        }
    });

    window.onkeyup = (e) => {
        if (e.key === " ") {
            this.executeShot();
        }

        if (e.key === "Control") {
            this.executeBarrier();
        }

        if (e.key === "ArrowLeft") {
            this.isArrowLeft = false;
        } else if (e.key === "ArrowRight") {
            this.isArrowRight = false;
        }
    });
};

const removeListeners = () => {
    window.onkeyup = window.onkeydown = null;
}
connexo
  • 53,704
  • 14
  • 91
  • 128