Search code examples
javascriptmethodsbindaddeventlistener

I'm triying to execute a function defined object property passing as a reference to addEventListener


If i change the code inside the anonymous function by an alert(i), everything works as it should. But when i pass alert as a reference callback and try to run it as callback(i) it dosn't work.

I have tryied using bind and this but didn't find how to make it work.

Using eval works, but i want to understand how to solve it in the rigth way.

objectEventCb = {
  click: alert
}

for (let j = 0; j < Object.keys(objectEventCb).length; ++j) {
    let keys = Object.keys(objectEventCb);
    sp[i].addEventListener(keys[j], function() {
        objectEventCb[keys[j]](i)
    });
}

This is part of a bigger function where sp[i] are all the span elements in a for loop .


Solution

  • Can you try with:

    objectEventCb = {
      click: (number) => alert(number)
    }
    

    I guess what you are passing to 'click' is not the callable alert() function, but other thing (haven't tried it). Anyway, the code I showed you is an anonymus function that makes sure you call alert as a function.