0

如何在 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;
    });
};

请指教,

4

1 回答 1

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;
    })
});
于 2013-11-14T23:43:36.733 回答