You need to make the event handler a member of the class to ensure it’s referenceable in both places:
import { Controller } from 'stimulus'
export default class extends Controller {
static targets = [ "wrapper" ]
connect() {
document.addEventListener("keydown", this.closeHandler.bind(this))
}
disconnect() {
document.removeEventListener("keydown", this.closeHandler.bind(this))
}
closeHandler(event) {
if (event.keyCode == 27) {
this.close();
}
}
close() {
this.wrapperTarget.style.display = 'none'
}
}
Why not make it a Stimulus action instead, though? If you define your modal somewhere along these lines:
<div data-controller="modal" data-action="keydown@window->modal#close">
<!-- ... -->
</div>
You could simplify your controller and you won’t have to manage event listeners manually:
import { Controller } from 'stimulus'
export default class extends Controller {
static targets = [ "wrapper" ]
close(event) {
if (event.keyCode == 27) {
this.wrapperTarget.style.display = 'none'
}
}
}