How do I change the sort order of a backbone collection after it has already been initialized?
Tried this: Doesn't work
collection.comparator = function () {
// new function
}
collectionObject.sort()
I don't think you are defining the comparator correctly. If you define a comparator, objects will be inserted into the collection in the right order.
Here is an example you can just run through firebug on a site with backbone loaded:
var Chapter = Backbone.Model;
var chapters = new Backbone.Collection;
chapters.comparator = function(chapter) {
return chapter.get("page");
};
chapters.add(new Chapter({page: 9, title: "The End"}));
chapters.add(new Chapter({page: 5, title: "The Middle"}));
chapters.add(new Chapter({page: 1, title: "The Beginning"}));
chapters.pluck('title');
# OUTPUT
# ["The Beginning", "The Middle", "The End"]
Notice how the comparator returns the value stored in the page attribute of each chapter. Backbone's collection sorting acts like a sortBy which uses strings or ints, and doesnt follow a traditional -1,0,1 comparator approach.
It should work if you call sort on the correct collection:
collection.comparator = function (item) {
return item.get('field');
};
collection.sort();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With