Reverse sort order with Backbone.js

前端 未结 15 939
不知归路
不知归路 2020-12-02 05:45

With Backbone.js I\'ve got a collection set up with a comparator function. It\'s nicely sorting the models, but I\'d like to reverse the order.

How can I sort the m

15条回答
  •  [愿得一人]
    2020-12-02 06:33

    The following worked well for me:

    comparator: function(a, b) {
      // Optional call if you want case insensitive
      name1 = a.get('name').toLowerCase();
      name2 = b.get('name').toLowerCase();
    
      if name1 < name2
        ret = -1;
      else if name1 > name2
        ret = 1;
      else
        ret = 0;
    
      if this.sort_dir === "desc"
        ret = -ret
      return ret;
    }
    
    collection.sort_dir = "asc";
    collection.sort(); // returns collection in ascending order
    collection.sort_dir = "desc";
    collection.sort(); // returns collection in descending order
    

提交回复
热议问题