如何正确反向排序 BackboneJs 集合?

问题描述

我有一个表格,其中显示了几个项目。

<table>
...
<th scope="col">Priority <a id="sort"><i class="fas fa-chevron-down"></i></a> <a id="sort2"> 
<i class="fas fa-chevron-up"></i></a></th>
...
</table>

优先级分别为整数值 1、2 和 3。 我正在尝试在单击按钮时对项目进行排序。我设法通过在我的视图中使用 collection.sort() 进行了一次排序,并且排序完美。如何通过单击 sort2 按钮反向排序?对此的任何帮助表示赞赏。谢谢。

app.views.ShareView = Backbone.View.extend({
el: ".page",initialize: function () {},events:{
    "click #sort" : "sort","click #sort2" : "sort2"
},sort: function (e){
    e.preventDefault();
    this.collection.comparator = 'priority_id';
    this.collection.sort();
    this.render();
},sort2: function (e){
  //reverse sort
}

 render: function () {
    template = _.template($('#share-template').html());
    this.$el.html(template(app.userShare.attributes));
 }
 });

解决方法

您需要使用 sort comparator 函数而不是 comparator 属性。这允许您指定比较器函数而不仅仅是属性。例如;

this.collection.comparator = function(firstModel,secondModel) {
   if(firstModel.priority_id > secondModel.priority_id) { // change to < in order reverse the order
      return -1;
   }
   else if(firstModel.priority_id === secondModel.priority_id) {
      return 0;
   }
   else {
      return 1;
   }
}
this.collection.sort();

在 BackboneJS 中,如果您需要附加功能,通常可以使用函数代替值。