Bind fonction and remove event

I would like to ask a question about the class syntax used in JavaScript to defined a method and remove an event in the contexte of Stimulus.

In all the documentation I have consulted, I have never seen the use of arrow functions. For example:

export default class extends Controller {
  connect() {
    document.addEventListener("click", this.boundFindFoo)
  }

  findFoo() {
    console.log(this.element.querySelector("#foo"))
  }
}

What seems strange to me is that I never see a “bound” method in the constructor like:

this.boundFindFoo = this.findFoo.bind(this) and secondly, I don’t see a removeEventListener in the disconnect method.

I tried to explain to my colleagues that it would be more judicious to use arrow functions to have the functions automatically bound, but they told me that it worked without. Moreover, they were not convinced of the usefulness of removing event listeners in the disconnect method, because I do not have enough technical knowledge to justify it. I am personally more familiar with React and I know that when I use classes in React, I systematically bind my methods in the constructor (unless I use arrow functions) and I destroy the event listeners when the component is unmounted.

That’s why I wanted to know if any of you technically know the reason to use or not use bind in a Stimulus controller and the usefulness or not of removing event listeners in the disconnect method.

More specifically, if i should use the bind function in the disconnect, in which case should i bind my functions in the connect or initialize ? And in which case it is not needed ?

Thank you in advance for your help.

1 Like

In stimulus you generally want to avoid using addEventListener and use the data-action on your HTML elements instead to call functions off of events. Check out the docs here
About your question for bind I have used this before and particularly when I want to pass a function to a JS framework maybe as a callback and keep the context of the controller so that I can access things like this.element etc.