tags:

views:

268

answers:

3

How can I pass a parameter to a jquery iterator function (or whatever they're called), like:

    var states = new Array();
    states.push(true);

    $(children).each(function(states) {
        if(this.depth>states.length)
        {
            states.push(this.collapsed);
        }
        else if (this.depth<states.length)
        {
            states.pop();
        }

        var collapsed=states[states.length-1];
    }
    );

The "states" parameter arrives either as an int or a boolean, never an array. Suggestions? I'd prefer not to declare states as global. (The code above resides inside of a method).

+3  A: 

the code could just use states as a closure; you could declare states locally to the parent method, and then reference it from inside the anonymous function you pass to each. In fact, absent any other bugs I'm not seeing, you could just change

$(children).each(function(states) {

to

$(children).each(function() {

and it'd work, without a global.

DDaviesBrackett
+2  A: 
getEachCallback = function(states) {
  return function() {
     if(this.depth>states.length)
    {
        states.push(this.collapsed);
    }
    else if (this.depth<states.length)
    {
        states.pop();
    }

    var collapsed=states[states.length-1];

  };
};

$(children).each(getEachCallback (states));
Daniel Moura
don't forget to semicolon the end of your variable declaration and return statement (the second and third last lines), or JSLint will hurt your feelings ;) I like the 'stackwise' declaration of the states variable.
DDaviesBrackett
@DDaviesBrackett: What is JSLint? You mean getEachCallback = function(states) { return function(){};}; ???
Daniel Moura
yes, that's what I meant - jslint is www.jslint.com, which is a mechanism for sanitizing JS so that you don't accidentally shoot yourself in the foot.
DDaviesBrackett
A: 

The parameter of the $.each() function is not the array itself, but the index of the current item. If you're pushing and popping you don't need that, so just leave out the parameter entirely.

states will be available to the inner anonymous function because it's a closure, so you should be fine changing function(states) to function()

mishac