When using the jQuery \"each\" function, is there a way to pass arguments to the function that is called ?
something.each(build);
function build(vars) {
}
You can accomplish the above using a closure. The .each function takes as an argument a function with two arguments, index and element.
You can call a function that returns a function that takes those two arguments, and store variables in there that will be referenced when the returned function executes because of JavaScript scoping behavior.
Here's an example:
// closureFn returns a function object that .each will call for every object
someCollection.each(closureFn(someVariable));
function closureFn(s){
var storedVariable = s; // <-- storing the variable here
return function(index, element){ // This function gets called by the jQuery
// .each() function and can still access storedVariable
console.log(storedVariable); // <-- referencing it here
}
}
Because of how JavaScript scoping works, the storedVariable will be reference-able by the returned function. You can use this to store variables and access in any callback.
I have a jsFiddle that also proves the point. Notice how the text output on the page is different than the HTML defined in the HTML pane. Look at how the function references the stored variable and appends that to the text
http://jsfiddle.net/QDHEN/2/
Here's the MDN page for closures for more reference https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures