Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I just implemented this last night.</p> <p>You can set a new collection <code>comparator</code> and then use the <code>sort</code> method on the collection. <code>sort</code> will fire a <code>reset</code> event, which you can use in your view to re-render the list.</p> <p>Here is my view, which contains a select box that allows the user to choose how to sort the data:</p> <pre><code>App.HouseListView = Backbone.View.extend({ el: '.house-list', initialize: function() { App.houseCollection.bind('reset', this.populateList, this); }, events: { 'change .sort':'sort', }, populateList: function(collection) { this.$('ul').html(''); _.each(collection.models, function(model) { var view = new App.HouseListElemView({model:model}); this.$('ul').append(view.el); }); }, sort: function(e) { var sort_by = $(e.srcElement.selectedOptions[0]).attr('data-sort-by'); App.houseCollection.comparator = function(house) { return house.get(sort_by); } App.houseCollection.sort(); }, }); </code></pre> <p>Hope this helps</p> <p>EDIT: Implemented <code>@mu is too short</code>'s suggestion:</p> <pre><code>App.Houses = Backbone.Collection.extend({ model: App.House, url: API_URL, _sort_by: 'price', sort_houses_by: function(sort_by) { this._sort_by = sort_by; this.sort(); }, comparator: function(house) { return house.get(this._sort_by); }, }); App.houseCollection = new App.Houses(); App.HouseListView = Backbone.View.extend({ el: '.house-list', initialize: function() { App.houseCollection.bind('reset', this.populateList, this); }, events: { 'change .sort':'sort', }, populateList: function(collection) { this.$('ul').html(''); _.each(collection.models, function(model) { var view = new App.HouseListElemView({model:model}); this.$('ul').append(view.el); }); }, sort: function(e) { var sort_by = $(e.srcElement.selectedOptions[0]).data('sort-by'); App.houseCollection.sort_houses_by(sort_by); }, }); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload