如何解决如何正确反向排序 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 中,如果您需要附加功能,通常可以使用函数代替值。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。