HTML and CSS Reference
In-Depth Information
Sorting tasks
The final change we will make is to sort tasks so that the ones due earliest are sorted first.
We will again use the date library for parsing and comparing dates, but we will use the stand-
ard
sort
method available on arrays to perform the sorting.
The
sort
method accepts a comparator as an argument. A comparator is a function that can
compare any two elements in an array and determine which ranks higher. A comparator
should return a value less than 1 to indicate the first element is higher, 0 if they are equal,
or a number greater than 1 if the second element ranks higher. Date objects already have a
compareTo
method that performs this task.
The sort method will compare the relevant items in the array to determine their relative or-
der. This does not mean comparing all items with one another due to the fact it can rely on
transitivity:
If A > B and B > C then A > C.
We can add sorting with a single line in the
loadTasks
method:
loadTasks : function() {
$(taskPage).find('#tblTasks tbody').empty();
storageEngine.findAll('task', function(tasks) {
tasks.sort(function(o1, o2) {
return Date.parse(o1.requiredBy).compareTo( Date.parse(o2.requiredBy));
});
$.each(tasks, function(index, task) {
if (!task.complete) {
task.complete = false;
}
$('#taskRow').tmpl(task).appendTo( $(taskPage).find('#tblTasks tbody'));
taskCountChanged();
renderTable();
});
}, errorLogger);
}