0

I have a backbone collection called Topics that in one instance in my app I would like sorted by a property I have called view_count.

Another instance of the Topics collection I want to be sorted by name alphabetically.

Currently, on the collection, I have a comparator:

  comparator: (topic) -> 
     return topic.get('view_count') * -1

When I want the collection to be sorted by name rather than view_count, what is an elegant way to override or change the comparator/sorting options? I have tried to declare the comparator function on each initialization of the Topics collection bu that doesn't seem to work correctly.

1
  • 1
    Similar question has been answered here link . Hope it will also be helpful for reference.
    – dvk317960
    Jun 10, 2014 at 18:35

1 Answer 1

1

Change your collection to:

var Topics = Backbone.Collection.extend({
  initialize: function(options) {
    this.sortProperty = options.sortProperty;
  },
  comparator: function(topic) {
    if(this.sortProperty == "view_count")
      return topic.get("view_count") * -1;
    else
      return topic.get("name");
  }      
});

then when you instantiate your collection:

var topics1 = new Topics({sortProperty : "view_count"});
var topics2 = new Topics({sortProperty : "name"});

You can also change the sorting property after initializing a collection using:

topics1.sortProperty = "name";
5
  • What happens when you multiply a string by -1? Jun 10, 2014 at 18:36
  • Why do you assume it's a string? The property name is a String for sure, but the actual model property could be of any value. It's up to the OP to decide how to do the actual sorting once he knows the value of sortBy. He can use if/else to further customize the comparator based on the value of sortBy but I think that's very obvious. Jun 10, 2014 at 18:43
  • Why would you expect something called "name" to be a number? Your example code as it stands will try to multiple a name string by -1 and that doesn't make any sense so your answer is woefully incomplete. Also, simply setting the sortBy property won't resort the collection. Jun 10, 2014 at 19:07
  • I updated the answer in case it wasn't obvious enough how to further customize the sorting. The question wasn't about how to to do sort/resort, it was about how to determine what model property to use in the sorting. Jun 10, 2014 at 19:16
  • I also renamed sortBy to sortProperty, not to confuse it with backbone's sortBy. This is meant to be a custom property. Jun 10, 2014 at 19:19

Not the answer you're looking for? Browse other questions tagged or ask your own question.