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?