Skip to content

Instantly share code, notes, and snippets.

@ryexley
Created August 27, 2012 20:55
Show Gist options
  • Save ryexley/3492140 to your computer and use it in GitHub Desktop.
Save ryexley/3492140 to your computer and use it in GitHub Desktop.
Backbone.js SortableCollection
(function (w) {
w.SortableCollection = Backbone.Collection.extend({
initialize : function () {
_.bindAll(this);
},
sortInfo : [],
comparator : function (a, b) {
for (i = 0; i < this.sortInfo.length; i++) {
var criteria = this.sortInfo[i];
var p1 = a.get(criteria.property);
var p2 = b.get(criteria.property);
if (p1 < p2) {
return (-1 * criteria.order);
}
if (p1 > p2) {
return (1 * criteria.order);
}
}
return 0;
},
sortBy : function (property) {
var newSort = [];
_.each(this.sortInfo, function (field) {
if (field.property === property) {
newSort.push({ property : field.property, order : field.order * -1 });
}
});
_.each(this.sortInfo, function (field) {
if (field.property !== property) {
newSort.push({ property : field.property, order : field.order });
}
});
this.sortInfo = newSort;
this.sort();
}
});
w.MySortableCollection = c.SortableCollection.extend({
sortInfo : [
{ property : 'Property1', order : -1 }, // descending
{ property : 'Property2', order : 1 } // ascending
]
});
// implement an instance of the collection
var sc = new w.MySortableCollection();
// sort it by a different field...
sc.sortBy('Property2');
}(this));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment