当我单击 th 时,我正在尝试对我的用户表进行排序。我的用户有:
- 名字
- 姓氏
- 年龄
- 身份证
当我单击 th 时,会发生一种排序,但是:
- 当我按名字或姓氏对用户进行排序时,它仅适用于 asc 方向。
- 当我按年龄对用户进行排序时,双向有效
任何的想法 ?
这是我的观点:
var UserListView = Backbone.View.extend({
el: ".page",
events: {
'click .delete': 'deleteUser',
'click th': 'sortItem',
},
initialize: function(){
this.users = new UsersCollection();
},
sortItem: function(ev) {
var that = this;
var field = ev.currentTarget.id;
this.users.sort_field(field);
this.render();
},
deleteUser: function(ev) {
var id = ev.currentTarget.dataset.userId;
var user = new UserModel({
id: id
});
user.destroy({
success: function() {
var userList = new UserListView();
userList.render();
}
})
},
render: function() {
var that = this;
this.users.fetch({
success: function(users) {
var template = _.template(UserListTemplate, {
users: users.models
});
that.$el.html(template);
}
});
}
});
还有我的收藏:
var UsersCollection = Backbone.Collection.extend({
model: UserModel,
url: "/users",
initialize: function() {
this._compar = 'id';
this._sortDir = 'asc';
},
comparator: function(user) {
console.log(this._sortDir);
return this._sortDir == 'asc' ? user.get(this._compar) : -user.get(this._compar);
},
sort_field: function(field) {
this._compar = field;
this._sortDir = this._sortDir == 'asc' ? 'desc' : 'asc';
this.sort();
}
});