I'm getting a bit stuck implemented a backbone comparator, I basically want to select different sorting methods based on the route and use the comparator to sort the collection. Ideally I want to keep the sorting logic encapsulated within the collection but seem to be getting stuck. For example
Requests = Backbone.Collection.extend({
model : Request,
comparator : function(ab) {
return -ab.id;
},
nooffers : function() {
return this.sortBy(function(ab) {
return ab.get('offers');
});
}
});
So by default it sorts based on the default comparator - but in my routing I wish to be able to resort e.g. do something like
routes : {
"" : "index",
'/ordering/:order' : 'ordering'
},
ordering : function(theorder) {
ordering = theorder;
if(theorder == 'nooffers') {
Request.comparator = Request.nooffers();
}
Request.sort();
listView.render();
howitworksView.render();
}
However in that case I get an error ('c.call is not a function') any ideas?
You have a few things wrong here.
This doesn't do what you think it does:
That executes the
nooffers
method and assigns its result toRequest.comparator
. ButsortBy
returns the sorted list:and setting that list as the comparator function doesn't do anything useful.
You want to change the assignment to use the function rather that its return value:
and change the function to be a valid comparator function:
Demo (run with your console open): http://jsfiddle.net/ambiguous/AAZCa/
But having someone from the outside fiddling with the collection's methods like that smells bad and you shouldn't do it. Instead, you should ask the collection to change its ordering with something like this:
Demo: http://jsfiddle.net/ambiguous/uM9av/
Or you could let the collection swap its own
comparator
to avoid all the conditional logic inside thecomparator
:Demo: http://jsfiddle.net/ambiguous/Pjfq2/
I wrote custom method in the collection which will take care of sorting both ascending and descending and also it also sorts records with alphanumeric appropriately
//you can sort by using the "Sort" method (look closely uppercase S for Sort method)