Home > Software design >  Basic JS Question, Arrow Function with a callback using parameters in addEventListener
Basic JS Question, Arrow Function with a callback using parameters in addEventListener

Time:04-13

I have a basic function here. I want to be able to pass parameters into it. However, it is being called by the addEventListener. Now, after reading on here and researching I got it to work so that if I put the TOP option in - it works. When I use the bottom option, just below it -it does not work. (Not if I want to use parameters). I just am wondering a basic explanation as to why the arrow function with a callback can take parameters, how is this going round exactly? Not sure I am explaining my question well.

for (i = 0; i < dots.length; i  ) {
  dots[i].addEventListener('click', (e) => imgChoose(e, i));
}

for (i = 0; i < dots.length; i  ) {
  dots[i].addEventListener('click', imgChoose);
}

var i = 0;

function imgChoose(e, i) {
  var test = dots[i].className;
  console.log(e);
}

CodePudding user response:

It's got nothing to do with arrow functions specifically, you can use normal functions too. What matters is that when addEventListener calls your function, it will pass in exactly one parameter: the event. If you want to then call a function with two parameters you can, but you must write that code yourself.

Here's how it would look with a regular function:

dots[i].addEventListener('click', function (e) { imgChoose(e, i) });

P.S.: as written, you have a single variable i which is being used for all the click callbacks. So they're all going to use the final value of i, which will be equal to dots.length. You should create i in the initialization of your loop, and make sure to use let, not var.

for (let i = 0; i < dots.length; i  ) {
  • Related