使用日期和优先级对Backbone.Collection进行排序

时间:2013-01-28 17:17:35

标签: javascript backbone.js

好的,我有一个集合了某个模型的对象,这个模型包含一个日期和一个优先级,我希望它按日期排序,然后按优先级排序,我目前用这种方式实现:< / p>

App.Collections.Tasks = Backbone.Collection.extend({
model: App.Models.Task,
comparator: function(model) 
{
  return model.get("date") + model.get("priority");
}
});

这是我的输出:

Get to the party  Edit Delete 1 Fri Feb 1
Get to the party  Edit Delete 2 Mon Jan 28
Go to the store  Edit Delete 4 Mon Jan 28
Go to the mall  Edit Delete 3 Tue Jan 29
Get to the party  Edit Delete 3 Tue Jan 29
Get to the party  Edit Delete 5 Tue Jan 29
Get to the party  Edit Delete 2 Wed Jan 30
Get to work  Edit Delete 5 Wed Jan 30

我希望早期的日期始终排在首位,所以2月的日期应该是最后的,我怎么能实现这个目标呢?

谢谢!

1 个答案:

答案 0 :(得分:1)

你可以这样做:

comparator: function(model1, model2) {
    return (model1.get("date") + model1.get("priority")) -
        (model2.get("date") + model2.get("priority"));
}

Documentation声明,返回的值应该是-1,0或1,但这不是早先强制的,任何值都可以解决问题。

修改

comparator: function(model1, model2) {
    var comp = (model1.get("date") + model1.get("priority")) -
        (model2.get("date") + model2.get("priority"));
    if (comp < 0) {
        return -1;
    } else if (comp > 0) {
        return 1;
    } else {
        return 0;
    }
}

现在代码正好遵循上述规范。如果这不能解决问题,那么问题不在比较器中。

修改

傻傻的我。我假设您在date中存储了一个unix时间,但显然你没有。减去字符串会产生NaN,因此不会进行排序。所以你现在需要做的就是将date转换为unix时间格式(或至少类似的东西),然后它应该正常工作。