0TTT0
0TTT0

Reputation: 1322

passing this through addEventListener

I have a function that was previously working; but I have to make it wait now with setTimeout. I thought I could just add an arrow function as the callback for the eventListener and still be able to pass this as the button for the context but I am getting an error.

button.addEventListener("click", () => {
    setTimeout(checkAndRespond,1500);
});

//This is the line that throws the error
checkAndRespond = async function () {
    ...
    const row = this.parentElement.parentElement;
    ...
}

How am I supposed to pass this into the inner function?
Is the setTimeout context being passed in as this to checkAndRespond?
Is there something i am not understanding about how arrow functions work?

Upvotes: 0

Views: 46

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138267

How am I supposed to pass this into the inner function?

Which this ? Arrow functions take the context (this) of their parent functions, which is the global scope in this case and for that this points to window. If you want to call a function dynamically inside a certain context (that is what the addEventListeners do) you have to use a regular function.

Is the setTimeout context being passed in as this to checkAndRespond?

No. You have to .bind the context manually:

 button.addEventListener("click", function() { // <- now we can work with this here
   setTimeout(checkAndRespond.bind(this), 1500); // <- and bind it
 });

Or you use the arrow functions behaviour as described above, and pass this as an argument:

 button.addEventListener("click", function() {
   setTimeout(() => checkAndRespond(this), 1500);
 });

 async function checkAndRespond(button) {
   //...
 }

Sidenotes:

You could also just use button instead of this, but that would probably be too easy.

checkAndRespond = is an undeclared (!!) variable, always declare them!

Upvotes: 2

Related Questions