JTravakh
JTravakh

Reputation: 166

Jquery .done timing

I have the following code - it's meant to dynamically construct a list of links to other things based off of a sql query. The record in sql contains a field formed like "itemX, itemY, Recipe - Z", where that last element is optional - the code feeds each list element into another sql query, and when it feeds in the last one (and gets null) it was supposed to just print that piece out. Instead, when I ran it, I kept getting the element prior to the one I want. The problem is fixed by just adding 1 to z, but I want to know why it's doing this.

 $("#components").html("<span>BUILDS FROM</span>");
 var componentslist = data[9].split(", ");
 for (var z = 0; z < componentslist.length; z++){
   $.getJSON("items.php", {item:componentslist[z]}).done(function(internald){
     if(internald === null){
       $("#components").append("<br\><span>"+componentslist[z+1]+"</span>");
     } else {
       $("#components").append("<br\><span class=\"crosslink\" title=\""+internald[0]+"\">"+internald[1]+" - "+internald[2]+"</span>");
     }
   });
 }

So if data[9] is

"item3, item4, Recipe - 5g"

it'll query those items and spit out

"Item 3 - 1g, Item 4 - 2g, Recipe - 5g"

but if on the nullcase I just used componentslist[z] it would say

"Item 3 - 1g, Item 4 - 2g, item4"

even though at that point in the loop z should be 2, not 1.

Upvotes: 0

Views: 71

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

It is a classic problem with closure variable usage

$("#components").html("<span>BUILDS FROM</span>");
var componentslist = data[9].split(", ");
for (var z = 0; z < componentslist.length; z++){
    (function(idx){
        $.getJSON("items.php", {item:componentslist[idx]}).done(function(internald){
            if(internald === null){
                $("#components").append("<br\><span>"+componentslist[idx+1]+"</span>");
            } else {
                $("#components").append("<br\><span class=\"crosslink\" title=\""+internald[0]+"\">"+internald[1]+" - "+internald[2]+"</span>");
            }
        });
    })(z)
}

Upvotes: 1

Related Questions