Sorting strings in reverse order with backbone.js

后端 未结 6 2006
南方客
南方客 2020-12-08 07:25

I\'m trying to sort a Backbone.js collection in reverse order. There are previous replies on how to do this with integers, but none with strings.

var Chapter         


        
6条回答
  •  抹茶落季
    2020-12-08 07:46

    There are two versions of the comparator function that you can use, either the sortBy version - which was shown in the example, which takes one parameter, or sort - which you can return a more standard sort function, which the documentation says:

    "sortBy" comparator functions take a model and return a numeric or string value by which the model should be ordered relative to others. "sort" comparator functions take two models, and return -1 if the first model should come before the second, 0 if they are of the same rank and 1 if the first model should come after.

    So in this case, we can write a different comparator function:

    var Chapter  = Backbone.Model;
    var chapters = new Backbone.Collection;
    
    chapters.comparator = function(chapterA, chapterB) {
      if (chapterA.get('title') > chapterB.get('title')) return -1; // before
      if (chapterB.get('title') > chapterA.get('title')) return 1; // after
      return 0; // equal
    };
    
    chapters.add(new Chapter({page: 9, title: "The End"}));
    chapters.add(new Chapter({page: 5, title: "The Middle"}));
    chapters.add(new Chapter({page: 1, title: "The Beginning"}));
    
    alert(chapters.pluck('title'));
    

    So you should get as a response:

    "The Middle", "The End", "The Beginning"
    

提交回复
热议问题