Created
June 6, 2013 18:44
-
-
Save craigmaslowski/5723883 to your computer and use it in GitHub Desktop.
UNTESTED - Sort Backbone Collection by up to three terms.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
sortBy: function (direction, primary, secondary, tertiary) { | |
this.models.sort(function (a, b) { | |
var aPrimary, aSecondary, aTertiary, bPrimary, bSecondary, bTertiary; | |
// setup return values according to the sort direction | |
var lessThan = (direction === 'asc') ? -1 : 1, | |
greaterThan = (direction === 'asc') ? 1 : -1; | |
aPrimary = a.get(primary); | |
bPrimary = b.get(primary); | |
if (secondary) { | |
aSecondary = a.get(secondary); | |
bSecondary = b.get(secondary); | |
} | |
if (tertiary) { | |
aTertiary = a.get(tertiary); | |
bTertiary = b.get(tertiary); | |
} | |
// sort by primary if they are different | |
if (aPrimary < bPrimary) | |
return lessThan; | |
else if (aPrimary > bPrimary) | |
return greaterThan; | |
// primary are not different so do secondary sort | |
if (aSecondary < bSecondary) | |
return lessThan; | |
else if (aSecondary > bSecondary) | |
return greaterThan; | |
// primary and secondary are not different so do tertiary sort | |
if (aTertiary < bTertiary) | |
return lessThan; | |
else if (aTertiary > bTertiary) | |
return greaterThan; | |
return 0; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment