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?

3
  • 2
    see all related questions - javascript+closures+loops Commented Jun 22, 2010 at 21:10
  • A very good answer can be found here: stackoverflow.com/questions/1552941/… Commented Jun 22, 2010 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 Commented Jun 23, 2010 at 14:57

1 Answer 1

3

You will need to do an closure:

var exec = (function(dest){
  return function(objResponse) {
     processResponse(objResponse, dest);
  }
 })(objRequest[loop].dest);
Sign up to request clarification or add additional context in comments.

1 Comment

That is bar none, the strangest notation I've every seen. But this closure thing, very informative! I've found more information here: jibbering.com/faq/notes/closures

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.