使用箭头在Knockout JS中对表进行排序

时间:2014-02-26 00:15:48

标签: jquery sorting knockout.js

我正在使用KnockoutJS创建一个可排序表。该表工作正常,但我希望当用户点击该特定标题时,向上箭头显示在列标题旁边。再次单击,向上箭头应朝下。首先,箭头应朝向“年龄”列。

现在,没有箭头出现。在我的代码中导致这种情况的原因是什么?

HTML:

<table>
<thead>
<tr data-bind="foreach: headers">
<td data-bind="click: $parent.sort, text: title">
    <span data-bind="if: arrowDown"> v </span>
    <span data-bind="if: arrowUp"> ^ </span>
</td>
</tr>
</thead>

淘汰赛:

var viewModel = function(){
    var self = this;
    self.people = ko.observableArray([
        {firstName:'James',lastName:'Smith',age:38},
        {firstName:'Susan',lastName:'Smith',age:36},
        {firstName:'Jeremy',lastName:'Smith',age:10},
        {firstName:'Megan',lastName:'Smith',age:7},
        {firstName:'James',lastName:'Jones',age:40},
        {firstName:'Martha',lastName:'Jones',age:36},
        {firstName:'Peggy',lastName:'Jones',age:10}
    ]);
    self.headers = [
        {title:'First Name',sortPropertyName:'firstName', asc:true, arrowDown: false, arrowUp: false},
        {title:'Last Name',sortPropertyName:'lastName', asc:true, arrowDown: false, arrowUp: false},
        {title:'Age',sortPropertyName:'age', asc:true, arrowDown: false, arrowUp: true}
    ];

    self.activeSort = self.headers[2];

    self.sort = function(header, event){
        if(self.activeSort === header) {
        header.asc = !header.asc;
        header.arrowDown = !header.arrowDown;
        header.arrowUp = !header.arrowUp;
        } else {
        self.activeSort.arrowDown = false;
        self.activeSort.arrowUp = false;
        self.activeSort = header;
        header.arrowDown = true;
        }
        var prop = header.sortPropertyName;
        var ascSort = function(a,b){return a[prop] < b[prop] ? -1 : a[prop] > b[prop] ? 1 : a[prop] == b[prop] ? 0 : 0; };
        var descSort = function(a,b){return a[prop] > b[prop] ? -1 : a[prop] < b[prop] ? 1 : a[prop] == b[prop] ? 0 : 0; };
        var sortFunc = header.asc ? ascSort : descSort;
        self.people.sort(sortFunc);
    };
};

ko.applyBindings(new viewModel());

2 个答案:

答案 0 :(得分:4)

使标题项的排序属性可观察,如果更改正常的javascript值,则knockout将不会更新UI。

self.headers = [ { 
    title: 'First Name', 
    sortPropertyName: 'firstName',
    asc: ko.observable(true),
    arrowDown: ko.observable(false),
    arrowUp: ko.observable(false)
}, ... ];

当您从sort函数设置时,knockout现在将更新UI。

答案 1 :(得分:-3)

如果您使用Datatables.net插件,它将为您节省所有麻烦。