1

I'm trying to attach an onchange event to a checkbox created by js.

I finally gotten the closure to work inside a for loop, but now it activates on load rather than on change.

Why is this?

https://jsfiddle.net/dkrh587h/2/

  chkbox.addEventListener("change", (function(newVarA, newVarB, newVarC, newVarD) {
    searchMap(newVarA, newVarB, newVarC, newVarD);
  }(gblStatus, "Status", statuser, chkbox.checked)), false);
Emwat
  • 116
  • 1
  • 15

1 Answers1

2

This is because you are invoking the function being passed as the second argument to addEventListener with the extra parenthesis.

This is sometimes called a self-executing function:

function() {
    // will get invoked immediately
}();

Variables like statuser will be available in your callback because of closure (assuming they are declared within a function-scope that "encloses" your posted code).

A pattern like this should work:

var statuser = 'my user'; // will be available in your callback
chkbox.addEventListener("change", function() {
  searchMap(gblStatus, "Status", statuser, chkbox.checked);
}, false);
Jonathan.Brink
  • 23,757
  • 20
  • 73
  • 115
  • That was my first problem. Whenever I tried that, I only got the last element in the for loop. – Emwat May 11 '16 at 19:08
  • @Emwat I see. That's a classic case of confusion with closures. I would recommend using `gblStatus.forEach` instead to avoid that problem. See this answer for information why that problem happens: http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – Jonathan.Brink May 11 '16 at 19:11