0

The code seems to fall apart in _handleEscClose when the close method is called, I'm pretty sure this is because of the "this" logic, but I cannot figure out an alternative method to close the popup via the escape key. Is there a way to provide the listener with the proper method without removing the ability to remove the event listener?

I think I worded this poorly, my issue is that _handleEscClose is not closing the popup, I believe it's because the call to this.close() is not working, and I'm having trouble getting it to work without using an arrow function in the eventlistener callback which then removes the ability to remove the eventlistener.

here's the relevant code

close() {
    this._popupElement.classList.add("invisible");
    document.removeEventListener("keydown", this._handleEscClose);
}

open() {
    this._popupElement.classList.remove("invisible");
    document.addEventListener("keydown", this._handleEscClose);
}

_handleEscClose(evt) {
    if (evt.key === "Escape") {
        console.log("Escape!");
        this.close();
    }
}

Tried swapping to an arrow function on the event listener but that seems to make the listener unremovable

I was able to solve it by changing _handeEscClose into an arrow function, instead of the the event listener callback.

_handleEscClose = (evt) => {
    if (evt.key === "Escape") {
        console.log("baba");
        this.close();
    }
}
  • [Call](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call) and [Apply](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply) are useful for controlling `this` during a function's execution. – Lonnie Best Apr 04 '22 at 20:44
  • Since you're adding the event listener to the document, it seems you'd be able to remove it at anytime, as long as you pass the correct arguments to [removeEventListener](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener). – Lonnie Best Apr 04 '22 at 20:46

0 Answers0