Have you ever wanted a quick code look up for sorting by columns in a table using Backbone.js? Also sorting those in ascending and descending orders? Then, you are at the right place!

As it is already known it is easy to implement sorting using rails at the backend but to avoid multiple API requests each time separately for ascending and descending orders, one can handle it at the Integration-Frontend using Backbone.js.

Sorting can be done with the attribute present in a column of a table. Column can be of type integer or string or any other data type. This doc will be helpful for integer and any other column of string type.

Please find the quick steps that can help for the sorting requirement if you come across for your application.

Pre-requisite: Before looking into the code for sorting, following points must be noted:

  1. In Backbone.js, list are referred as collections. So as the models (objects) are created, these gets added to the list i.e. “collection.models”.

  2. Every actions must be registered in the event listeners function mappings in order to map the event with reference to class of an HTML element to the related action methods. (Note: Mapped method name should exactly match the calling method name).

In View.js, ensure the following mappings are done:

Here, by specifying onclick attributes, browser expects functions that are mapped against an HTML element which is clicked.

  events: {
    'click .asc_sort_by_name': 'asc_sort_by_name',
    'click .desc_sort_by_name': 'desc_sort_by_name',
  },
  1. It is important to initialise the “listenTo” function of sort otherwise the events of sorting is not executed. Basically, it tells the current object (this) to listen to an event(sort) on a collection.
  initialize: function() {
    this.listenTo(this.collection, "sort", this.render);
  },
  asc_sort_by_name: function(){
    this.collection.byNameAsc();
  },

Now in collection.js file, these action method implementation is done by using “comparator”. This comparator is used to sort the items in the collection.

  byNameAsc: function(){
    this.comparator = function(model) {
      // Logic for ascending sorting based on the data type
    }
    this.sort();
  },
  byNameDesc: function(){
    this.comparator = function(model) {
      // Logic for descending sorting based on the data type
    }
    this.sort();
  },

For integer type: This is one of the easiest sorting of all data types.

For ascending: Include the column name to be sorted by against “get” function.

  byIdAsc: function(){
  this.comparator = function(model) {
       return model.get(id);
     }
     this.sort();
   }

For descending: Include the column name to be sorted by against “get” function. Note the “-“ minus sign here in order to reverse the collections based on column.

    byIdDesc: function(){
      this.comparator = function(model) {
        return -model.get(id);
      }
      this.sort();
    }

For String type: This one has same ascending order logic as that of Integer type but slightly additional logic for descending is required. For descending order, need to include logic for comparisons between two models from the collection and sort accordingly.

For ascending: Include the column name to be sorted by against “get” function.

    byNameAsc: function(){
      this.comparator = function(model) {
           return model.get('name');
       }
      this.sort();
    },
  

For descending: Include the column name to be sorted by against “get” function.

    byNameDesc: function(){
      this.comparator = function(model1, model2) {
         if (model1.get('name') > model2.get('name')) return -1; // before
         if (model2.get('name') > model1.get('name')) return 1; // after
         return 0; // equal
        }
      this.sort();
    },
  

And just to save your some more time on Front end , the following HTML piece of code can be used in template:

Let us suppose Name is a column: Here the class name is used as reference to an element in event mapping of the action methods as mentioned in pre-equisite section.

  <th>Name
     <a class="asc_sort_by_name"><i class="fa fa-arrow-up"></i></a>
     <a class="desc_sort_by_name"><i class="fa fa-arrow-down"></i></a>
  </th>

These “fa fa-arrow-up” and “fa fa-arrow-down” are the part of application.css using https://fontawesome.com/?from=io.

This is just a handy code snippet for a newbie and an experts too.

References: 1 . Backbone.js Documnetation: http://backbonejs.org/#Collection-comparator

2 . For the String reverse order implementation: https://code-examples.net/en/q/5602cc