Only last AJAX request in sorted table sorts

On this issue, I created the following sample solution: http://jsfiddle.net/PKcnb/3/ ,

The code requests 50 videos (due to request restrictions) through the YouTube API. Each query adds a new row to the summary table. I need a simple sorting solution, so I used jquery.sortElements.js.

sortElement.js seems to work, but this is only sorting the video from the last request made. Why not sort the entire table? Searching around, it seems I need to implement .live () , but my attempts were unsuccessful.

Corresponding jQuery

// Recursive function to grab the next set of videos function getVideos(index, max) { $.ajax({ url: 'https://gdata.youtube.com/feeds/api/playlists/UUAuUUnT6oDeKwE6v1NGQxug?v=2&orderby=duration&max-results=50&start-index=' + index, // 'https://gdata.youtube.com/feeds/api/users/tedtalksdirector/uploads', dataType: "xml", success: function(xml) { var videos = $(xml).find("entry"); videos.each(function() { var title = $(this).find("title").text(); var duration = $(this).find("duration").attr("seconds"); var minutes = Math.floor(duration / 60); var seconds = (duration % 60); if (seconds < 10) seconds = "0" + seconds; var newRow = $("<tr></tr>"); newRow.append("<td>" + title + "</td>"); newRow.append("<td class='dur'>" + duration + "</td>"); $("tbody#videos").append(newRow); }); newIndex = index + 50; $('#VideosLoaded').html(newIndex - 1); if (newIndex < max) { getVideos(newIndex, max); } } }); } // Make table sortable (jquery.sortElements.js) // via https://stackoverflow.com/questions/5066002/sending-one-ajax-request-at-a-time-from-a-loop var table = $('table'); $('#Title, #Duration').wrapInner('<span title="sort this column"/>').each(function() { var th = $(this), thIndex = th.index(), inverse = false; th.click(function() { table.find('td').filter(function() { return $(this).index() === thIndex; }).sortElements(function(a, b) { return $.text([a]) > $.text([b]) ? inverse ? -1 : 1 : inverse ? 1 : -1; }, function() { // parentNode is the element we want to move return this.parentNode; }); inverse = !inverse; }); });​ 
0
source share
1 answer

I think the sorting procedure will work better:

 $('#Title, #Duration').wrapInner('<span title="sort this column"/>').each(function() { var th = $(this), thIndex = th.index(), inverse = false; th.click(function() { table.find('td').filter(function() { return $(this).index() === thIndex; }).sortElements(function(a, b) { var id = th.attr('id'), a = (id === 'Duration') ? parseInt($(a).text()) : $(a).text(), b = (id === 'Duration') ? parseInt($(b).text()) : $(b).text(), x = (a === b) ? 0 : (a > b) ? 1 : -1; return (x === 0) ? 0 : inverse ? -x : x; }, function() { return this.parentNode; }); inverse = !inverse; }); }); 

Updated fiddle

+1
source

All Articles