Skip to content

Instantly share code, notes, and snippets.

@bcinarli
Last active August 29, 2015 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bcinarli/974b0d40ca778f075516 to your computer and use it in GitHub Desktop.
Save bcinarli/974b0d40ca778f075516 to your computer and use it in GitHub Desktop.
Backbone collection sort
var app = app || {};
(function(){
"use strict";
app.Collection = Backbone.Collection.extend({
model: app.Model,
// initial sort when collection fetched first time
comparator: "id"
});
app.collection = new app.Collection();
})();
var app = app || {};
(function(){
"use strict";
app.View = Backbone.View.extend({
events: {
"click .sortable": "sortTable"
},
initialize: function(){
this.$list = this.$(".sortable-table");
// your initialize script
},
render: function(){
// your render actions
},
/**
* sample sortable table is like
* <table class="sortable-table">
* <thead>
* <tr>
* <td class="asc" data-sort="id">ID</td>
* <td data-sort="name">Name</td>
* <td data-sort="order">Order</td>
* </tr>
* </thead>
* <tbody>
* ...
* <tbody>
* </table>
*/
sortTable: function(e){
e.preventDefault();
var $e = $(e.currentTarget),
sortBy = $e.data("sort"),
direction = $e.hasClass("asc") ? "desc" : "asc";
// note that, for rendering, only "tbody" should re-render,
// and thead part will remain same.
// the asc/desc classes could be used both for direction in
// rendering and also displaying the sort direction arrows
this.$list.find(".sortable").removeClass("asc desc");
$e.addClass(direction);
sortCollection(this.collection, sortBy, direction);
};
});
})();
/**
* Backbone Collection comparator modifier
* Modifies the comparator method according to given column name and the directions
* By default, collection sorted according to "id" in ascending order.
* @param sortBy
* @param direction
*/
sortCollection = function(collection, sortBy, direction) {
collection.comparator = function(item1, item2) {
if(direction === "desc") {
return item1.get(sortBy) > item2.get(sortBy) ? -1 : 1;
}
return item1.get(sortBy) > item2.get(sortBy) ? 1 : -1;
};
collection.sort();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment