我正在用KnockoutJS创建一个可排序的表。该表工作正常,但是当用户单击特定标题时,我希望在标题上方显示一个向上箭头。再次单击,向上箭头应朝下。首先,箭头应在“年龄”(Age)列上朝上。
现在,没有箭头出现。是什么导致这种情况在我的代码中发生?
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());
最佳答案
使标题项上的排序属性可观察,如果您更改常规的javascript值,则剔除将不会更新UI。
即
self.headers = [ {
title: 'First Name',
sortPropertyName: 'firstName',
asc: ko.observable(true),
arrowDown: ko.observable(false),
arrowUp: ko.observable(false)
}, ... ];
当您从sort function中设置此功能时,淘汰赛将立即更新UI。