views:

61

answers:

4

I have a HTML table like this:

<table>
 <tr><td>X</td><td>X</td><td class='latest order1'>X</td><td class='latest order4'>X</td></tr>
 <tr><td>X</td><td>X</td><td class='latest order3'>X</td><td class='latest order2'>X</td></tr>
 <tr><td>X</td><td>X</td><td class='latest order6'>X</td><td class='latest order5'>X</td></tr>
</table>

Now, I want to run a jQuery action (an ajax call) on all objects of latest class, that's a simple:

$('.latest').each(do_call());

But since the ajax action takes some time, I have the elements ordered by their importance. And I would like to run the do_call() for object with order1, then for order2 element, and so on.

How can I sort jQuery objects, so the actions would run in proper order?

A: 

I think you can find AJAX QUEUE plugin usefull. From the manual:

Ajax Queue is a plugin that helps to manage Ajax race conditions. When multiple Ajax requests are made in rapid succession, the results can be returned out of order. This can cause weird behavior in your application. Ajax Queue is a plugin (actually, 2 plugins) that provide a way to manage these requests.

Ivan Nevostruev
+1  A: 

this can probably be more efficient but it should do what you are looking for:

var latestItems = $('.latest');
var order = 1;
for(var i = -1, len = latestItems.length; ++i < len ) {
    var item = $('.latest .order' + order);
    doCall.call(item);
    order++;
}
Jared
+1  A: 

First, get all the .latest elements and their order classes in an array:

var order = [];

$('.latest').each(function() {
    // Get the order - all elements have class 'latest orderX':
    // remove the 'latest', get the classname, and add the latest back.
    order.push($(this).removeClass('latest').attr('class'));
    $(this).addClass('latest');
});

Then sort the array and loop through it, get the corresponding element:

order.sort();

for(var i in order) {
    var obj = $('.latest.'+order[i]);
    do_call(obj);
}

This method works even if your .latest elements are not sequentially indexed; eg. you can have order4 after order1 with no order2 or order3 present and it still works.

Tatu Ulmanen
Why the `.attr('class')`? Is it necessary?
Mickel
Well, yes, if you want to get the classname of the element.
Tatu Ulmanen
Ok, but doesn't ´attr´ chained with ´addClass´ return a jQuery-object?
Mickel
@Mickel, you're right, the addClass should be on it's own. Fixed.
Tatu Ulmanen
+1  A: 

Why not do it all in one 'big' ajax call instead of running separate ajax calls for each element? Figure out a way to consolidate your data in such a way that it be separated on the server side and a have a single response update the elements on the client.

karim79
because if an ajax call takes ~30seconds to 5 minutes, I prefer doing it in smaller chunks - just to be able to update and display the result for most important parts faster.
kender