Monday, 26 August 2013

Javascript - passing variables with an array

Javascript - passing variables with an array

I'm working with some code I've adapted from and there's something I don't
quite understand the best way to do. I'm trying to streamline a bit of
code with different sorting functions that are applying sorts for specific
values to an array of list items.
At the moment the function does a compare based on a specific factor and
then returns the values to sort.
I want to pass two additional variables with this array/sort call but I
can't seem to work out the way to write this. At the moment I'm doing it
in a nasty way by having global variables on the window, but I'd rather
pass the variables directly.
Based on the code below, any ways to tighten & clean it up would be
appreciated:
arr = [];
sort_func = $j(this).children(':selected').val();
$j('li.collectionItem').each(function(){
arr.push(this);
});
if (sort_func == "a_z")
{
window.dataType = 'alpha';
window.bigFirst = false;
arr.sort(sort_products);
}
else if (sort_func == "z_a")
{
window.dataType = 'alpha';
window.bigFirst = true;
arr.sort(sort_products);
}
// custom sort functions
function sort_products(a, b)
{
dataType = window.dataType;
bigFirst = window.bigFirst;
var compA = $j(a).data(dataType);
var compB = $j(b).data(dataType);
if (bigFirst == true)
{
return (compA > compB) ? -1 : (compA < compB ) ? 1 : 0;
}
else
{
return (compA < compB) ? -1 : (compA > compB ) ? 1 : 0;
}
}

No comments:

Post a Comment