Wait for .each() .getJSON request to finish before executing a callback
I have a jquery .each
loop that retrieves remote data from a json request for all the elements on a page with a certain class. One set of the elements is a group of li
tags that I would like to sort using another function after the li
element has been updated with the remote information.
Passing in the sort function after the .each
loop does not sort the list because the items have not finished lo开发者_Go百科ading from the json request. The sorting works If I pass in the sort function as a .complete
callback for the getJSON request but I only want the sort to run once for the whole list, not for each item.
fetch_remote_data(function(){sort_list_by_name();});
function fetch_remote_data(f){
jQuery('.fetching').each(function(){
var oj = this;
var kind = this.getAttribute('data-kind');
var url = "http://something.com"
jQuery.getJSON(url, function(json){
$(oj).text(json[kind]);
$(oj).toggleClass('fetching');
});
});
if (typeof f == 'function') f();
};
Any suggestions?
If you're using jQuery 1.5, you could take advantage of its $.Deferred implementation:
function fetch_remote_data(f) {
var requests = [],
oj = this,
url = "http://something.com";
$('fetching').each(function() {
var request = $.getJSON(url, function(json) {
$(oj).text(json['name']);
$(oj).toggleClass('fetching');
});
requests.push(request);
});
if (typeof f === 'function')
$.when(requests).done(f);
}
// No need to wrap this in another function.
fetch_remote_data(sort_list_by_name);
I'm assuming the $('fetching')
bit in your example isn't real code? That selector would be searching for <fetching>
elements in the DOM, which probably isn't what you want.
Try to get the total number of fetches to be be performed before fireing each(). Than attach the .complete callback in which you first increase some count of completed requests and sort only if the number of completed equals to the total number to be performed. In principle, you should run sort only after all ajax called has finished...K
精彩评论