I have an array of object that I’m trying to iterate over and build markup for a list from. I’m using an array to store the deferred requests and $.when to inject the concatenated markup into the DOM after all the request have been completed.
Here’s the code:
function populateItemList(items) {
var output = '',
item = null,
template = null,
defers = [];
for (var i = 0, j = items.length; i < j; i++) {
item = items[i];
defers.push(function() {
$.get('/item/' + item.id + '/template')
.done(function(source) {
template = Handlebars.compile(source);
output += template(item);
console.log(item.id + ': done');
})
});
}
$.when.apply(window, defers).done(function() {
$('.itemListContainer').html(output);
$('.itemList a').click(onItemLinkClick);
console.log('when: ' + output);
});
}
However, I’m not having any success. I’m running into one of two problems:
- If I do wrap the deferred items in a function (as in the code above), the requests do not get executed, but the $.when does. But since the requests didn’t get executed, the output is empty.
- If I don’t wrap the deferred items in a function, the requests get executed (the correct number of times, but the item.id logged to the console is always the id of the last item), and the $.when does not get executed.
I’m aware that this is very similar to this question, and I’m using that code as a basis for mine, but I’m still having these problems. Any ideas?
When you wrap the code in a function like that, the code never gets executed. What you push into the array is a reference to the function, not the result of the AJAX call.
When you don’t wrap the code in a function it does get executed, but as you are using the local variable
itemin the callback, you will be using the value that the variable has at the time that the responses arrive, not when the request was sent. As the requests are asynchronous, and because Javascript is single threaded, no callbacks will be called until you have returned from thepopulateItemListfunction, so theitemvariable will always be the last item.You should wrap the code in a function, that will let you create an
itemvariable for each iteration, but you should also execute the function immediately, and push the return value into the array: