如何在knockoutjs模型中使用计算字段对observableArray进行排序?我想用计算字段排序。这是字段:
self.filteredCases = ko.computed(function () {
return ko.utils.arrayFilter(self.cases(), function (onecase) {
return ((self.eventFilter() == 1 && onecase.Status() == self.statusFilter())
|| (self.eventFilter() != 1 && onecase.Status() == self.eventFilter())
|| ((self.eventFilter() == 1 && self.statusFilter() == 0)
&& (onecase.Status() == 1 || onecase.Status() == 2 || onecase.Status() == 3 || onecase.Status() == 4))
);
});
});
所以我想只对过滤的项目进行排序,而不是所有项目。项目排序正在运行,但似乎ko.computed没有排序方法。
我有更多列,这里是一个过滤方法:
self.orderById = function (direction) {
self.cases.sort(function (left, right) { //Working
//self.filteredCases().sort(function (left, right) { //Do nothing
return direction ?
left.CaseId() > right.CaseId() ? 1 : -1
: left.CaseId() < right.CaseId() ? 1 : -1;
});
};
请建议,
答案 0 :(得分:0)
这很简单。只需对过滤后的数组进行排序。
self.filteredCases = ko.computed(function () {
var filter = ko.utils.arrayFilter(self.cases(), function (onecase) {
return ((self.eventFilter() == 1 && onecase.Status() == self.statusFilter())
|| (self.eventFilter() != 1 && onecase.Status() == self.eventFilter())
|| ((self.eventFilter() == 1 && self.statusFilter() == 0)
&& (onecase.Status() == 1 || onecase.Status() == 2 || onecase.Status() == 3 || onecase.Status() == 4))
);
});
return filter.sort();
//Optionally, you can pass a function to sort,
//Which takes a left and right parameter
//And returns -1/1 for before/after
return filter.sort(function(left, right) {
return left.Status() > right.Status() ? 1 : -1;
})
});