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 loading 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:
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.