简体   繁体   中英

JavaScript: Passing changing parameters to a callback

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?

You will need to do an closure:

var exec = (function(dest){
  return function(objResponse) {
     processResponse(objResponse, dest);
  }
 })(objRequest[loop].dest);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM