Reverse sort order with Backbone.js

前端 未结 15 976
不知归路
不知归路 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: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.

提交回复
热议问题