Backbone Paginator Server Sorting

Recently I had to sort a collection using server mode (that is, doing a fetch for each page). It turns out this was not a simple as it seemed, needing to pass some extra options to the mode switching to stop the state being lost (as I could not set the pagination mode on the parent).

This is because I had some trouble with inheritance since I was using a child and parent collection. Here is the solution I found: (note the options in switchMode)

let parentCollection = Backbone.PageableCollection.extend({
  queryParams: {
    currentPage: ‘current_page’,
    pageSize: ‘page_size’,
    totalPages: ‘count’,
    sortKey: ‘sort’,
  },
})

let childCollection = parentCollection.extend({
  url: ‘/documents’,
  model: Entities.Document,
  comparator: Entities.DocumentCollectionComparator,

  doSort(field = ‘modified’, mode) {
    this.setSorting(field, mode === ‘des’ ? 1 : -1, {full: true})
    this.switchMode(‘server’, {fetch: true, resetState: false});
    this.sort()
  },
});

Leave a Reply

Your email address will not be published. Required fields are marked *