Last active
October 13, 2015 20:07
-
-
Save kjantzer/4248444 to your computer and use it in GitHub Desktop.
Backbone.js: sortable collection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var SortableCollection = Backbone.Collection.extend({ | |
//key: 'LocalStorageKey', // define a key for saving sort info to local storage | |
//defaultSort: 'some_key', // the default key to sort by | |
defaultDesc: false, | |
localStoreKey: function(extra){ | |
return 'list:'+this.key+(extra?':'+extra:''); | |
}, | |
/* | |
Sort Key - defaults to "release date" | |
*/ | |
sortKey: function(newKey){ | |
if(newKey !== undefined) | |
amplify.store('list:'+this.key+':sort', newKey); | |
else | |
return amplify.store('list:'+this.key+':sort') || this.defaultSort; | |
}, | |
/* | |
Sort Descending | |
*/ | |
sortDesc: function(desc){ | |
if(desc !== undefined) | |
return amplify.store('list:'+this.key+':sort:desc', desc); | |
else | |
return amplify.store('list:'+this.key+':sort:desc') || this.defaultDesc; | |
}, | |
/* | |
Sort By - overriding default sort by behaviour to add in reverse order logic | |
*/ | |
sortBy: function(){ | |
var models = _.sortBy(this.models, this.comparator, this); | |
if(this.sortDesc()) | |
models.reverse(); | |
return models; | |
}, | |
/* | |
Comparator - How to sort; | |
*/ | |
comparator: function(model){ | |
return model.get( this.sortKey() ); | |
}, | |
/* | |
Change how this collection is sorted | |
*/ | |
changeSort: function(sortKey){ | |
// if same sort key was clicked, lets reverse the sort direction | |
if(this.sortKey() == sortKey) | |
this.sortDesc( !this.sortDesc() ); // set direction to opposite of what it is now | |
// set the new sort key | |
this.sortKey( sortKey ); | |
this.trigger('sort:change'); | |
// re-sort the collection | |
this.sort(); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://www.benknowscode.com/2013/12/multi-column-sort-in-backbone-collections.html