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

hrysbysz  于 2022-11-24  发布在  其他
关注(0)|答案(1)|浏览(123)

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

<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));
 }
 });
q3qa4bjr

q3qa4bjr1#

您需要使用排序比较器函数,而不是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中,如果需要额外的功能,通常可以使用函数代替值。

相关问题