0

i have the following code working fine:

let elements = document.querySelectorAll('.click-target');

function handler(ev) {
    console.log(ev.target.id);
    this.classList.toggle('selected');
}

elements.forEach(element => element.addEventListener('click', handler, true));

Unfortunately i don't get this code working using an arrow-function within the addEventListener:

elements.forEach(element => element.addEventListener('click', ev => {
    handler(ev).bind(element);
}));

The result: this is undefined. Although i've read a lot about the JS 'this' i have to confess, i'm still not able to master this in a way i should. Please can anybody try to explain me in a simple and stupid way what i'm doing wrong?

Many thanks in advance, Slevin

Slevin
  • 617
  • 1
  • 7
  • 17
  • 1
    With `ev => {`, you've already lost the calling context of the element the listener is bound to. You can't use an arrow function there. (also, `bind` creates a function, but doesn't call it.) – CertainPerformance May 24 '20 at 20:00
  • Furthermore `handler(ev)` will execute that function and you're calling `.bind` on the return value of that function. Since there is no explicit `return` statement the function call implicitly produces `undefined`. You should be getting an error there. – VLAZ May 24 '20 at 20:03

0 Answers0