10

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) {

}

I know that I can simply do the following, but I was wondering if there is a way in which arguments can be passed directly.

something.each(function() {
    build(vars);
);
5
  • 1
    stackoverflow.com/questions/5033861/… Commented Sep 20, 2013 at 7:31
  • 8
    I know that I can simply do the following - that is how you do it. Commented Sep 20, 2013 at 7:31
  • I think there is no other way the other question is: what is your purpose to do this in another way? Commented Sep 20, 2013 at 7:45
  • @Martin Just for better looking code, no other functional reason. Commented Oct 3, 2013 at 19:49
  • using partial function you can - stackoverflow.com/a/17509456/1060656 Commented Feb 12, 2014 at 22:53

1 Answer 1

25

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.