【问题标题】:cant sort collection in a descending fashion无法以降序方式对集合进行排序
【发布时间】:2014-10-28 15:07:54
【问题描述】:

我正在尝试使用.sort() 对我的集合进行排序,但是我似乎只能以升序对集合进行排序,集合的代码是这样的,

    var ProjectCollection = Backbone.Collection.extend({

    url: '/projects',
    model: app.Project,
    sort_key: "finish_date",

    comparator: function (item) {
        return item.get(this.sort_key);
    },

    sortByField: function(fieldName, orderType) {
        console.log(fieldName, orderType);
        this.sort_key = fieldName;
        if(orderType == "acsending") {
            this.sort(function(a, b){return a-b});
        } else if(orderType == "descending") {
            this.sort(function(a, b){return b-a});
        }
    }

});

sortByField 函数在选择菜单更改时从视图中触发,并触发此函数,

sortCollection: function(e) {

        this.collection.sortByField($('.sort').val(), $('.order').val());
        console.log(this.collection);

    }

为什么我不能按降序排序?发送到集合函数的参数是正确的,并且 if 和 if else 会根据这些参数正确运行。

【问题讨论】:

    标签: javascript sorting backbone.js backbone.js-collections


    【解决方案1】:

    您应该使用sortBy() 方法而不是sort()

    正如documentation 中所述,sort() 方法只是重新排序集合(就像每次插入新模型时所做的那样)并发出“排序”事件。

    sortBy() 方法接受将定义订单的函数 Comparator(如您的示例中所示)(documentation)。考虑一下,而不是写

    function(a, b){return a-b}
    

    你应该写这样的东西

    function(a, b){return a.get("field")-b.get("field")}
    

    这样您比较对象的字段而不是对象的toValue() 方法的结果。

    【讨论】:

      【解决方案2】:

      您的模型未按降序排序,因为 sort() 不接受比较器回调(请参阅文档中的 sortBy())

      您需要将您的逻辑放入comperator() - 请参阅此示例:http://jsbin.com/petetiwiqo/1/edit?html,js,output

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-01-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多