How do I change the sort order of a backbone collection after it has already been initialized?
Tried this: Doesn't work
collectionparator = function () {
// new function
}
collectionObject.sort()
How do I change the sort order of a backbone collection after it has already been initialized?
Tried this: Doesn't work
collection.parator = function () {
// new function
}
collectionObject.sort()
Share
Improve this question
asked May 20, 2011 at 3:02
HarryHarry
55.1k76 gold badges187 silver badges270 bronze badges
2
- Is defining the parator when the collection is intialized not an option? Why not? – Matt Ball Commented May 20, 2011 at 3:21
-
Post more code. How is
collection
andcollectionObject
defined? – hyperslug Commented May 20, 2011 at 5:58
2 Answers
Reset to default 3I don't think you are defining the parator correctly. If you define a parator, 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.parator = 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 parator 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 parator approach.
It should work if you call sort on the correct collection:
collection.parator = function (item) {
return item.get('field');
};
collection.sort();