Backbone/Underscore sortBy is not sorting collection

前端 未结 3 1441

I have a list of users (six to be exact) in a collection with \'firstname\', \'lastname\' properties. Doing a fetch, the comparator below sorts them by \'firstname\', and it wor

相关标签:
3条回答
  • 2021-02-04 15:45

    To respond to your update:

    If you're wanting to change the order that the collection is sorted in for use by it's corresponding view then you could just update the comparator and then call sort to get the model re-sorted. This will then fire a sort event which your view can listen for and update itself accordingly.

    this.collection.comparator = function (user) {
      return user.get("firstname").toLowerCase();
    };
    
    this.collection.sort();
    
    0 讨论(0)
  • 2021-02-04 15:57

    The sortBy function does 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.

    0 讨论(0)
  • 2021-02-04 15:58

    Underscore's sortBy which Backbone uses, returns the sorted collection not sort 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);
    
    0 讨论(0)
提交回复
热议问题