I am converting a Modal to use Stimulus.
When the modal is connected, I add a EventListener to listen for the escape key to close the modal. Thats working fine.
When I open another modal on the same page I want to remove the EventListener.
As I understand it should go in the disconnected() function.
But how do I address the ‘esc’ function there?
import { Controller } from 'stimulus'
export default class extends Controller {
static targets = [ "wrapper" ]
connect() {
const esc = (e) => {
if (e.keyCode == 27) {
this.close();
}
}
document.addEventListener("keydown", esc)
}
disconnect() {
// this of course doesnt work
// document.removeEventListener("keydown", esc)
}
close() {
this.wrapperTarget.style.display = 'none'
}
}