Saturday, 12 August 2017

jquery - Javascript how to store predefined function (with arguments)











I have the following:



function test(a,b,c){
console.log(a+b+c);
}

for (var i=0; i < array.length; i++){
steps.push(
function(){ test(array[i].something, array[i].wow, i);}
);


I want to store functions with several parameters, and bind them to buttons later when the DOM is loaded



for (var i=0; i    $('#mydiv li a').eq(i).click(steps[i]);

}


It's not really working since steps[i] contains do(array[i].something, array[i].wow, i); instead of do('bob', 'john', 1) for example



I have tried using the .apply javascript function but it will execute in the loop, instead of storing them


Answer



Closures can help you here. Here's one solution to the first bit of code:



function do(a,b,c){

console.log(a+b+c);
}
for (var i=0; i < array.length; i++){
(function (i) {
steps.push(
function(){ do(array[i].something, array[i].wow, i);}
);
})(i);
}



There's no "block scope" in Javascript, just function scope. With your code, each function you pushed into the steps array had a reference to the last value of i, not the one it had when the function was pushed into steps. Invoking an immediately executing function enables the pushed function to have a value for i that doesn't change, because a closure is being created. And this closure has a value for i that is independent of the loop's value for i, which will be whatever is the last index of array.


No comments:

Post a Comment

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...