-
Notifications
You must be signed in to change notification settings - Fork 174
Extended Sorting Functions
Ken Moini edited this page Aug 29, 2013
·
1 revision
A guide to some further examples of extending StupidTable's sorting functions into real-world applications
So say you have a directory listing populating a table such as the following, where you have an Up/Parent Directory link that should stay at the top, and two groups of row types, directories and files, identified by a class. Ideally, the directory listing should be sorted but kept above the sorted file listing.
<table id="dirListingTable" class="table-striped table table-hover" border="0" width="100%">
<thead><tr>
<th class="detailsFilename" data-sort="string-ins">Filename</th>
<th class="detailsSize" data-sort="int">Size</th>
</tr></thead>
<tbody>
<tr class="upDir"><td colspan="2"><a href="?dir=/">.. (Up Dir)</a></td></tr>
<tr class="directory">
<td><a href="?dir=/cgi-bin">cgi-bin</a></td>
<td class="detailsSize" data-sort-value="0"></td>
</tr>
<tr class="directory">
<td><a href="?dir=/docs">ktk</a></td>
<td class="detailsSize" data-sort-value="0"></td>
</tr>
<tr class="directory">
<td><a href="?dir=/pics">pics</a></td>
<td class="detailsSize" data-sort-value="0"></td>
</tr>
<tr class="file">
<td><a href="?download_file=/backup.zip">backup.zip</a></td>
<td class="detailsSize" data-sort-value="2027236">2 MB</td>
</tr>
<tr class="file">
<td><a href="?download_file=/mirc.zip">mirc.zip</a></td>
<td class="detailsSize" data-sort-value="2027220">2 MB</td>
</tr>
</tbody>
</table>
The Javascript...
var sortStupid = jQuery("#dirListingTable").stupidtable();
sortStupid.bind('aftertablesort', function (event, data) {
// Move Up Dir link to the top & group by directory and files
var rowsObjs = $(this).find("tbody tr"); //Find the rows in this stupidtable
var rows = rowsObjs.slice(0); //Separate them into an array
var dirRows = []; //Inititalize a few arrays
var fileRows = [];
var newRows = [];
for(r=0; r<rows.length; r++) {
if (jQuery(rows[r]).hasClass('directory')) { dirRows[dirRows.length] = rows[r]; } //Add the rows that have a 'directory' class to the newly initialized 'dirRows' array.
else if (jQuery(rows[r]).hasClass('file')) { fileRows[fileRows.length] = rows[r]; } //If it's matched as a file by the row having a 'file' class, then add it into the 'fileRows' array
else if (jQuery(rows[r]).hasClass('upDir')) { newRows[0] = rows[r]; } //Or, if this is the 'Parent Directory' link, then place it at the beginning of the 'newRows' array.
}
for(d=0; d<dirRows.length; d++) { newRows[newRows.length] = dirRows[d]; } //First loop through the newly populated 'dirRows' array, then add them to the 'newRows' array.
for(f=0; f<fileRows.length; f++) { newRows[newRows.length] = fileRows[f]; } //Do the same for the files
$(this).children("tbody").append($(newRows)); //Then lastly update the DOM
});