Reverse sort order with Backbone.js

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

    Modify your comparator function to return some reversely proporitional value instead of returning the data that you are currently. Some code from : http://documentcloud.github.com/backbone/#Collection-comparator

    Example:

    var Chapter  = Backbone.Model;
    var chapters = new Backbone.Collection;
    
    /* Method 1: This sorts by page number */
    chapters.comparator = function(chapter) {
      return chapter.get("page");
    };
    
    /* Method 2: This sorts by page number in reverse */
    chapters.comparator = function(chapter) {
      return -chapter.get("page");
    };
    
    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"}));
    

提交回复
热议问题