0

While implementing a closure function, I have noticed that if I provide a "named function" as an event handler then it gets executed straightaway when the event gets attached to the buttons. However, if I keep the function inline as an anonymous function then it doesn't execute straightaway and fires only on the event happens. Please can anyone explain this behaviour?

var buttons = document.getElementsByTagName('button');

//function buttonHandler(buttonName){
////  return function(){
////    console.log(buttonName);
//// }
//  alert("hello");
//}

var buttonHandler = function(name){
  alert(name);
}

for(var i = 0; i < buttons.length; i += 1) {
 var button = buttons[i];
 var buttonName = button.innerHTML;
 button.addEventListener('click', buttonHandler(buttonName));
  button.addEventListener('click', function(buttonName){
          alert("hi");
      });
}

Many Thanks!

S Saad
  • 111
  • 1
  • 3
  • Uncomment your code and remove this var buttonHandler stuff. You simply call buttonHandler, thats why it does not do what you expect – Jonas Wilms Jun 23 '17 at 10:10

2 Answers2

0

This has nothing to do with the function being named. This is about your code explicitly calling the function.

If you put (some,arguments) after a function then you will call it.

!foo() // calls the function
!function () { }(); // Also calls the function

So:

button.addEventListener('click', buttonHandler(buttonName));
  1. Calls buttonHandler, passing buttonName as an argument to it
  2. Calls addEventListener, passing "click" and the return value of 1 to it

buttonHandler has no return statement, so that return value of undefined which isn't a useful thing to pass to addEventListener.

The commented out version of buttonHandler returns a function. That would be a useful thing to pass to addEventListener.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Thanks for the explanation. Can I also ask in your answer you mentioned "Calls addEventListener, passing "click" and the return value of 1 to it" why is it passing the return value of 1? Second, why do you have ! prefexing foo() and !function(){}(); – S Saad Jun 23 '17 at 10:34
  • Because item 1 in the list describes the part of the code which generates that return value. https://stackoverflow.com/questions/3755606/what-does-the-exclamation-mark-do-before-the-function – Quentin Jun 23 '17 at 10:43
-1

As pointed out in the answers above the code

button.addEventListener('click', buttonHandler(buttonName));

is making direct call the function so if you only need to pass parameters to the handler function you may use an anonymous function instead of directly calling the function as recommended here (https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener)

I updated my code as below

button.addEventListener('click', function (){ buttonHandler(buttonName)}, false);
S Saad
  • 111
  • 1
  • 3