Skip to content

Instantly share code, notes, and snippets.

@isochronous
Created May 22, 2015 22:25
Show Gist options
  • Save isochronous/9a90c7343f957f05a81c to your computer and use it in GitHub Desktop.
Save isochronous/9a90c7343f957f05a81c to your computer and use it in GitHub Desktop.
A client-side comparator generating function for Backbone collections
/**
* This method creates a new comparator function that should correctly sort by the right field in the correct order
* assuming the sorting is specified by a single field with a "attributeName-asc/desc" format. Add as a change handler
* for your sortBy field, add `this.on('sync', this.sort)` to the collection, and you're ready to go.
* @param {Backbone.Model} model
* @param {string} newSortBy
* @deprecated
*/
updateCollectionComparator: function(model, newSortBy) {
var theCollection = this.someCollection, // change this line
parts = newSortBy.split('-'),
fieldPart = parts[0],
attrName = fieldPart.charAt(0).toLowerCase() + fieldPart.slice(1),
dir = parts[1].toLowerCase();
theCollection.comparator = function (one, two) {
var oneVal = one.get(attrName),
oneId = one.id,
twoVal = two.get(attrName),
twoId = two.id;
// If all else is equal, sort by aggregateVersion
if (oneVal === twoVal) {
if (oneId === twoId) { return 0; }
if (dir === 'asc') {
return oneId < twoId ? -1 : 1;
} else {
return oneId > twoId ? -1 : 1;
}
}
if (dir === 'asc') {
return oneVal < twoVal ? -1 : 1;
} else {
return oneVal > twoVal ? -1 : 1;
}
};
this.console.log('Updated event collection to sort %s on %s', dir, attrName);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment