3

Now here's a fun problem. I have an object array as the following:

objRequests = [
   {
      url: "/cgi-bin/script1.cgi",
      dest: "#div1"
   },
   {
      url: "/cgi-bin/script1.cgi",
      dest: "#div2"
   }
];

Now, I iterate through these objects to load some information from the server at particular addresses using jQuery's $.getJSON() method and after some fancy mangling through the callback function, needs to put HTML into the div whose id is specified via 'dest'.

Normally, if I need to specify extra data to go into the callback, I'd use an anonymous function, and that works just fine. The problem here is that the variable pointer for destination seems to remain the same, so destination is always equal to "#div2" when each callback fires.

I've tried the following:

for (var loop = 0; loop < objRequest.length; loop++)
{
    var exec = new function(objResponse)
    {
       processResponse(objResponse, objRequest[loop].dest);
    }

    exec.dest == objRequest[loop].dest;

    $.getJSON(objConfig.strTicketScript, exec);
}

as well as

for (var loop = 0; loop < objRequest.length; loop++)
{
    var destination = objRequest[loop].dest;

    var exec = new function(objResponse)
    {
       processResponse(objResponse, destination);
    }

    exec.dest == objRequest[loop].dest;

    $.getJSON(objConfig.strTicketScript, exec);
}

but for some reason Firefox still doesn't seem to create individual data in the anonymous function. Is there a way to get a unique reference to data on each iteration?

RandomInsano
  • 1,204
  • 2
  • 16
  • 36
  • 2
    see all related questions - [javascript+closures+loops](http://stackoverflow.com/questions/tagged/javascript+closures+loops) – Anurag Jun 22 '10 at 21:10
  • A very good answer can be found here: http://stackoverflow.com/questions/1552941/variables-in-anonymous-functions-can-someone-explain-the-following – Shog9 Jun 22 '10 at 23:15
  • Both great links. Thanks for the info. I had some trouble searching since I didn't know what to search for :S – RandomInsano Jun 23 '10 at 14:57

1 Answers1

3

You will need to do an closure:

var exec = (function(dest){
  return function(objResponse) {
     processResponse(objResponse, dest);
  }
 })(objRequest[loop].dest);
azatoth
  • 2,379
  • 15
  • 18
  • 1
    That is bar none, the strangest notation I've every seen. But this closure thing, very informative! I've found more information here: http://www.jibbering.com/faq/notes/closures/ – RandomInsano Jun 23 '10 at 14:19