Reverse sort order with Backbone.js

前端 未结 15 901
不知归路
不知归路 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
    
    0 讨论(0)
  • 2020-12-02 06:33

    For reverse order on id:

    comparator: function(object) { return (this.length - object.id) + 1; }
    
    0 讨论(0)
  • 2020-12-02 06:35

    Backbone.js's collection comparator relies on the Underscore.js method _.sortBy. The way sortBy is implemented ends up "wrapping" up javascript .sort() in a way that makes sorting strings in reverse difficult. Simple negation of the string ends up returning NaN and breaks the sort.

    If you need to perform a reverse sort with Strings, such as reverse alphabetical sort, here's a really hackish way of doing it:

    comparator: function (Model) {
      var str = Model.get("name");
      str = str.toLowerCase();
      str = str.split("");
      str = _.map(str, function(letter) { 
        return String.fromCharCode(-(letter.charCodeAt(0)));
      });
      return str;
    }
    

    It's by no means pretty, but it is a "string negator". If you don't have any qualms with modifying native object types in javascript, you could make you code clearer by extracting the string negator and adding it as a method on String.Prototype. However you probably only want to do this if you know what you are doing, because modifying native object types in javascript can have unforeseen consequences.

    0 讨论(0)
提交回复
热议问题