# Add and remove EventListeners

**URL:** <https://discuss.hotwired.dev/t/add-and-remove-eventlisteners/710>\
**Category:** General\
**Created:** [March 20, 2019, 7:38am UTC](https://discuss.hotwired.dev/t/add-and-remove-eventlisteners/710 "2019-03-20T07:38:09Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![kaspermeyer](https://yyz1.discourse-cdn.com/flex027/user_avatar/discuss.hotwired.dev/kaspermeyer/32/483_2.png) [@kaspermeyer](https://discuss.hotwired.dev/u/kaspermeyer)\
**Post date:** [March 20, 2019, 8:21am UTC](https://discuss.hotwired.dev/t/add-and-remove-eventlisteners/710/2 "2019-03-20T08:21:46Z")

</div>

You need to make the event handler a member of the class to ensure it’s referenceable in both places:

```javascript
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:

```auto
<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:

```javascript
import { Controller } from 'stimulus'

export default class extends Controller {
  static targets = ["wrapper"]

  close(event) {
    if (event.keyCode == 27) {
      this.wrapperTarget.style.display = 'none'
    }
  }
}

```

---

_[View the full topic](https://discuss.hotwired.dev/t/add-and-remove-eventlisteners/710)._
