You can see each list item has multiple attributes data-whatever. The user will choose from a dropdown box on how things should be sorted and the appropriate method is called. Is eval()
the most appropriate choice for this or is there a better way?
$('#sort-options').change(function() {
var sortType = $(this).val();
var $selectedList = $($(".drop-zone.ui-tabs-selected a").attr('href')).find('.connectedSortable');
var $listItems = $('li', $selectedList);
//Sort
var sortFunction = null;
switch (sortType) {
case 'custom':
$listItems.sort(sortCustom);
break;
case 'breed':
$listItems.sort(sortBreed);
break;
case 'hatch':
$listItems.sort(sortHatch);
break;
case 'laid':
$listItems.sort(sortLaid);
break;
default:
$listItems.sort(sortCustom);
}
//Empty UL
$selectedList.empty();
//Repopulate UL
$.each($listItems, function(index, $listItem) {
$selectedList.append($listItem);
});
});
function sortCustom(a, b) {
return $(a).attr('data-sort-order') - $(b).attr('data-sort-order');
}
function sortBreed(a, b) {
return $(a).attr('data-breed') - $(b).attr('data-breed');
}
function sortHatch(a, b) {
return $(a).attr('data-hatch') - $(b).attr('data-hatch');
}
function sortLaid(a, b) {
return $(a).attr('data-laid') - $(b).attr('data-laid');
}
//Force initial sort
$('#sort-options').trigger('change');
}
return $(a).attr('data-breed') - $(b).attr('data-breed');
can be replaced withreturn a.getAttribute('data-breed') - b.getAttribute('data-breed');
which is 10X faster. \$\endgroup\$