Search code examples
javascriptclosureslexical-scope

Javascript - Closures - Lexical Scoping - How to include a loop variable data in nested function?


Possible Duplicate:
Javascript infamous Loop problem?

I have the following code:

function test() {

   var columns = options.columns;

for (var i =0; i < columns.length; i++) {
    if (columns[i].type === "number") {
        var field = columns[i].field;
        columns[i].footerTemplate = function(data) { return buildFooter(data, field);     };
      }
  }
}

function buildFooter(data, field) {
   alert(field);
 }

A library function calls the footerTemplate function (which in turn call buildFooter). The alert in buildFooter states that field is always the same value (the last value iterated in for loop of test.) How can buildFooter be called with the appropriate field value (i.e.

 columns[0].footerTemplate = function(data) { return buildFooter(data, columns[0].field);} 

and

 columns[1].footerTemplate = function(data) { return buildFooter(data, columns[1].field);}

and so on...


Solution

  • Try:

    columns[i].footerTemplate = (function(field) {
        return function (data) {
            buildFooter(data, field);
        };
    })(field);
    

    It immediately executes a function that returns a new function that has the correctly bound field variable. It's definitely a scope issue that is a problem with loops, so using an immediately invoked function to create a new scope and making the correct variables available. This is definitely a duplicate of Javascript infamous Loop issue? though