Massive / Underscore sortBy does not sort the collection

I have a list of users (more precisely, six) in the collection with the properties "firstname", "lastname". Performing the selection, the comparator below sorts them by "first", and it works fine.

comparator : function (user) { return user.get("firstname").toLowerCase(); } 

But if I try to sort the collection later, with a different value, that is, "lastname", this will not work. The order remains the same.

 this.collection.sortBy(function(user) { return user.get("lastname").toLowerCase(); }); 

What am I doing wrong?


Update


This way, the data returned from sortBy IS is sorted, but that does not help me, since my view is related to the collection. If I reset the collection and add the sorted array back to the collection, the comparator will do this and sort it in the "firstname" order.

 var sorted = this.collection.sortBy(function(user) { return user.get("lastname").toLowerCase(); }); 
+8
javascript
source share
3 answers

The sortBy function sortBy not sort the objects in the current collection. It returns a sorted collection:

 var sortedCollection = this.collection.sortBy(function(user){ return user.get("lastname").toLowerCase(); }); 

Now you can use sortedCollection and it will be sorted correctly.

+11
source share

To respond to your update:

If you want to change the sort order of the collection to use in the corresponding view, you can simply update the comparator and then call sort to get the model re-sorted. Then the sort event will fire, which your view can listen to and update accordingly.

 this.collection.comparator = function (user) { return user.get("firstname").toLowerCase(); }; this.collection.sort(); 
+13
source share

Emphasize sortBy , which uses Backbone, returns a sorted collection without sorting it in place ... To illustrate:

 var flinstones = [{first: 'Baby', last: 'Puss'}, {first: 'Fred', last: 'Flinstone'}]; var sorted = _.sortBy(flinstones, function (character) { return character.last ; }); console.log(sorted); console.log(flinstones); 
+3
source share

All Articles