-1

(A note to the moderators - a similar question has been answered here stackoverflow link. Although the problem was solved, a proper explanation was missing regarding what was causing the problem)

The Problem -

Below is simple code. which displays an alert when link is clicked.

const linkVar = document.getElementById("theLink");
linkVar.addEventListener("click", listnerFunction);

function listnerFunction() {
  alert("case 1");
}
<a id="theLink" href="#">click here to call the listner function</a>

Next, a small change is made, I would like to pass the alert text when call to function is made.

const linkVar = document.getElementById("theLink");
linkVar.addEventListener("click", listnerFunction("Case 2"));

function listnerFunction(passedText) {
  alert(passedText);
}
<a id="theLink" href="#">click here to call the listner function</a>

This Case 2 causes the problem. Now on running the case 2 code. the alert shows without clicking and on clicking the alert doesn't show.

The Question - when an argument is passed to the listener function what really happens?

Deski Rey
  • 131
  • 2
  • 10
  • `const listenerFunction = text => () => alert(text)` - You'll have to change the first one to `listenerFunction('case 1')` though - Or you can use a default argument, `const listenerFunction = (text = "defaultText") => () => alert(text)` – Mulan Jun 22 '19 at 12:55

2 Answers2

2

When you use parenthis after a function reference like so functionName() you're telling JS to call the function with the name functionName. So, in your case, you are calling listnerFunction() when you add your event listener:

// --------------------------------\/\/\/\/\/\/\/\/ -- executes listnerFunction()
inkVar.addEventListener("click", listnerFunction("Case 2"));

Thus, this really evaluates to:

inkVar.addEventListener("click", undefined);

As listnerFunction("Case 2") returns undefined (as nothing is returned from it)

In order to do what you're after you can wrap your function call in its own (anonymous) function, such that the (anonymous) function can execute your function call which is then able to pass through your desired argument:

inkVar.addEventListener("click", function() {
  listnerFunction("Case 2");
});
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
1

When you are doing this:

    linkVar.addEventListener("click", listnerFunction("Case 2"));

you are passing the result of calling listnerFunction("Case 2") to addEventListener not the function itself as you do in the first case.

What you'll want to do is this:

    linkVar.addEventListener("click", () => listnerFunction("Case 2"));
Jonathan Rys
  • 1,782
  • 1
  • 13
  • 25