Changing the sort order of a backbonejs collection?

How to change the sort order of the core network after it has already been initialized?

Tried this: not working

collection.comparator = function () { // new function } collectionObject.sort() 
+6
source share
2 answers

I do not think you are defining a comparator correctly. If you define a comparator, the objects will be inserted into the collection in the correct order.

Here is an example that you can simply run through firebug on a site with a loaded database:

 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. Sorting trunk collections acts like sortBy, which uses strings or ints and does not follow the traditional -1.0,1 comparison approach.

+3
source

It should work if you call sorting by the correct collection:

 collection.comparator = function (item) { return item.get('field'); }; collection.sort(); 
+2
source

Source: https://habr.com/ru/post/888609/


All Articles