Accessing the class "this" inside addEventListenter

Hey all!

Inside the connect(), I need to use window.addEventListener('click', functionName). The issue is, inside the functionName, I no longer have access to the class’s this:

static targets = [ "foo" ]

connect {
  window.addEventListener('click', this.toggle)
}

disconnect() {
  // I'll need to disconnect
  // window.removeEventListener('click', this.toggle)
}

toggle(event) {
  // this is undefined -> this.fooTarget
}

Yes, it will be undefined as it’s now the "windows’ scope, within the listener function, but how to achieve what I want?

EDIT:

Never mind. I need to use bind :sweat_smile:

[..]

connect {
  window.addEventListener('click', this.toggle.bind(this))
}

[..]
1 Like

Another way is to use an arrow function

toggle = (event) => {
  console.log(this)
}
2 Likes

I strongly recommend doing your bind calls in your initialize function:

initialize () {
  this.toggle = this.toggle.bind(this)
}

Not only does this save you from calling .bind(this) over and over again, when you’re removing your event listener you can pass in this.toggle and it will be pointing to the same instance, which is necessary for removing the listener.

What you have to remember is that .bind() is a function that returns a new function, so if you call it multiple times for the same function, it will be a different copy each time.

Calling .bind() in initialize is memoizing the returned value.

2 Likes