Dhruv Chadha Dhruv Chadha - 1 year ago 102
Javascript Question

Why can't we pass parameter in eventListener's listener function?

function myFunc(parameter1) {
//function definition
document.getElementById("some Id").addEventListener("click", myFunc(myparameter));

Why is it that I cant pass a parameter to myFunc() function inside the eventListener? I know I can use this way -

document.getElementById("some Id").addEventListener("click", function() {

But why can't I do it directly ?

PS- I want to know whether the rules prescribed by W3C are to be followed directly (and I shouldn't ask this question) or is there a reason behind every rule ?

Answer Source

myFunc(myparameter) executes the function right now, not when the event is triggered. You want to pass a function which executes myFunc and passes the parameter when called, i.e. when the event is triggered. The most straight forward way to do that is this:

.addEventListener('click', function () { myFunc(myparameter); })

The perhaps less obvious way is Function.prototype.bind:

.addEventListener('click', myFunc.bind(null, myparameter))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download