Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbonejs collection change sort order?

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()
like image 507
Harry Avatar asked May 20 '11 03:05

Harry


2 Answers

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.

like image 148
Jake Dempsey Avatar answered Oct 23 '22 23:10

Jake Dempsey


It should work if you call sort on the correct collection:

collection.comparator = function (item) {
  return item.get('field');
};

collection.sort();
like image 23
hyperslug Avatar answered Oct 23 '22 23:10

hyperslug