views:

40

answers:

1

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?

+1  A: 

You will need to do an closure:

var exec = (function(dest){
  return function(objResponse) {
     processResponse(objResponse, dest);
  }
 })(objRequest[loop].dest);
azatoth
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