0

I'm using StimulusJS for my js and I would like to be able to remove a listener when a user go to a new page.

So far I have created what it seems good for me

import { Controller } from "stimulus"


export default class extends Controller {
  connect() {
    this.addListenerCloseModal()
  }

  disconnect() {
    this.removeListenerCloseModal()
  }

  addListenerCloseModal() {
    window.addEventListener('click', this.closeModal)
  }

  removeListenerCloseModal() {
    window.removeEventListener('click', this.closeModal, true)
  }

  closeModal(event) {
    var modal = document.getElementById("myModal");

    if (event.target == modal) {
      modal.style.display = "none";
    }
  }
}

But the problem is the listener is still there. I have read that comment about bind and this Javascript removeEventListener not working but I don't really understand it . It seems like I should have a global variable which is binding my this.closeModal but how can I have a global variable in my class ?

Gaeguri
  • 455
  • 4
  • 19

1 Answers1

0

It's not the case of anonymous functions. You're asking the browser to remove the event listener defined as capturing listener since your removeEventListener call has third true parameter. The browser can't find it because the event was added as non-capturing with false as default third parameter.

So in simple words adding and removing the same event should match the capturing state. See Matching event listeners for removal

Lyzard Kyng
  • 1,518
  • 1
  • 9
  • 14