0
   for (var i=0 ; i<10 ; i++){

      var myFunction = function(something){
         console.log(i);
      }

      $.ajax({

        url: "something.json",
        dataType: "json",
        success: function( response ) {

               myFunction(response.something);

        }
      });               

    }

How do I access latest i in myFunction every time when loop through the for loop. It seems that the latest i in myFunction is not accessible, so it does not log from i = 0 to 9.

Terry Chen
  • 427
  • 6
  • 9

3 Answers3

1

This probably is not the most efficient solution. But it does work. You can set object variables to the request and access them by using .call on myFunction

for (var i=0 ; i<10 ; i++){

  var myFunction = function(something){
     console.log(this.localData.i);
  }

  $.ajax({
      url: "/echo/json/",
      dataType: "json",
      //Set the i variable to this request
      localData: {
          i: i
      },
      success: function( response ) {
        //call myFunction with this as the context, and you'll be able to access localData by using this.localData.i
        myFunction.call(this, response.something)
      }
  });               

}

Heres a fiddle: http://jsfiddle.net/XxRAv/1/

bottens
  • 3,834
  • 1
  • 13
  • 15
0
      function myFunction(i,something){
         console.log(i);
         console.log(something);
      }

    for (var i=0 ; i<10 ; i++){
      $.ajax({

        url: "something.json",
        dataType: "json",
        success: function( response ) {

               myFunction(response.something);

        }
      });               

    }
john Smith
  • 17,409
  • 11
  • 76
  • 117
0

You're seeing the effects of late binding. One solution is to create a wrapper function and call it which will return the correct function:

  var myFunction = function(i){ 
     return function(something){ console.log(i); };
  }(i);
mgilson
  • 300,191
  • 65
  • 633
  • 696