sortingbackbone.jscodeigniter-3backbone.js-collections

How to properly reverse sort a BackboneJs collection?


I have a table where several items are displayed.

<table>
...
<th scope="col">Priority <a id="sort"><i class="fas fa-chevron-down"></i></a> <a id="sort2"> 
<i class="fas fa-chevron-up"></i></a></th>
...
</table>

The priorities holds an integer value, 1, 2 and 3 respectively. I'm trying to sort the items on button click. I managed to sort once by using collection.sort() in my view and it sorts perfectly. How can i reverse sort by clicking sort2 button? Any help regarding this is appreciated. Thank you.

app.views.ShareView = Backbone.View.extend({
el: ".page",

initialize: function () {},

events:{
    "click #sort" : "sort",
    "click #sort2" : "sort2"
},

sort: function (e){
    e.preventDefault();
    this.collection.comparator = 'priority_id';
    this.collection.sort();
    this.render();
},

 sort2: function (e){
  //reverse sort
}

 render: function () {
    template = _.template($('#share-template').html());
    this.$el.html(template(app.userShare.attributes));
 }
 });

Solution

  • You need to use the sort comparator function instead of the comparator property. This allows you to specify a comparator function instead of just the property. For example;

    this.collection.comparator = function(firstModel, secondModel) {
       if(firstModel.priority_id > secondModel.priority_id) { // change to < in order reverse the order
          return -1;
       }
       else if(firstModel.priority_id === secondModel.priority_id) {
          return 0;
       }
       else {
          return 1;
       }
    }
    this.collection.sort();
    

    In BackboneJS, it is often possible to use a function in place of a value if you require additional functionality.