Sorting a collection of base groups After initialization

I use Backbone.js to display a list of items, like books. After the list is displayed, there are options for sorting users. Therefore, if the user clicks the "Sort by title" or "Sort by author name" button, the list will be sorted on the client side.

window.Book = Backbone.Model.extend({ defaults: { title: "This is the title", author: "Name here" }, 

What is the best way to accomplish this view using Backbone in the context of the application. Am I using jQuery dom sorter in AppView?

+48
Aug 10 '11 at 3:01
source share
4 answers

There will be a discussion on this topic, which you can look at: https://github.com/documentcloud/backbone/issues/41 .

In short, when the user selects "sort by X", you can:

  • Define the comparator function in the collection
  • Call the Collection sort function (which raises the sort event)
  • Listen for the sort event in your view and (clear and) redraw the elements

Another way to handle steps 1 and 2 is to have your own method that calls the Collection sortBy method and then fires a custom event that your view can view.

But it seems like clearing and redrawing is the easiest (and possibly the fastest) way to sort your view and synchronize with the sort order of the collection.

+47
Aug 10 '11 at 17:30
source share

You can update the comparator function and then call the sort method.

 // update comparator function collection.comparator = function(model) { return model.get('name'); } // call the sort method collection.sort(); 

The view will be automatically redrawn.

+42
Jan 10 2018-12-11T00:
source share

comparator is what you need

 var PhotoCollection = Backbone.Collection.extend({ model: Photo, comparator: function(item) { return item.get('pid'); } }); 
+10
Aug 10 '11 at 5:25
source share

This method works well and allows you to dynamically sort by all attributes and handle ascending or descending :

 var PhotoCollection = Backbone.Collection.extend({ model: Photo, sortByField: function(field, direction){ sorted = _.sortBy(this.models, function(model){ return model.get(field); }); if(direction === 'descending'){ sorted = sorted.reverse() } this.models = sorted; } }); 
+3
Oct 27 '15 at 4:03
source share



All Articles