Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function call with parameters to addEventListener inside a loop [duplicate]

Tags:

javascript

Problem : I would like to call a function "test " with passing parameters using the click event of the button.

using addEventListener ('click', test ); works.

using addEventListener ('click', test(parameter)); the function is activated automatically when loading and not to click on the button .

Question: how to pass parameters ?

//create 3 button (n is a counter):
    var btn = document.createElement("INPUT");
        btn.setAttribute("id", "demo"+n);
        btn.setAttribute("type", "button");
        btn.setAttribute("value", ("click"));
        document.body.appendChild(btn);

call Without parameters works correcty:

function test(m) {
    alert("YOU CLICKED ME!");
}

var m=0;
while(m!=3){
        document.getElementById("demo"+m).addEventListener("click", test);
        m=m+1;
}   

`

with parameters not works (the function is activated immediately):

function test(m) {
    alert("YOU CLICKED ME!"+m);
}

var m=0;
while(m!=3){
    document.getElementById("demo"+m).addEventListener("click", test(m));
            m=m+1;
}   
like image 377
MrEnrich Avatar asked Feb 10 '23 02:02

MrEnrich


1 Answers

Wrap your function in another function to avoid invoking it immediately

document.getElementById("demo"+m).addEventListener("click",(function(x){
    return function(){
        test(x);
    }
})(m));

In your case addEventListener expects a function object so you can't use parenthesis in front of function as it invokes the function and passes the returning value. So you need to return the function object which invokes test function( using an anonymous function to avoid closure property of javascript functions)

EDIT: Reason for returning wrapper function of test using an anonymous function

We can't pass

function(){
    test(m);
}

to addEventListener directly. As every function object in javascript remembers the environment( in our case variable m) outside their lexical scope . If you just create different function(like in while loop) in same environment( variable m ) then they will reference to same environment.

You have two use a function factory to avoid creating closures in loop like described above.

like image 143
bugwheels94 Avatar answered Feb 12 '23 15:02

bugwheels94