1
我正在使用Knockout創建可排序的表。表綁定,排序功能和過濾工作正常。不過,我想在特定列處於活動狀態時顯示排序圖標。
由於span已經綁定到標題數組中的可見屬性,並且此屬性是可觀察的,所以當此值更改(在排序函數中)時,UI應該更新,但不是。什麼可能導致這個? 這裏是的jsfiddle:http://jsfiddle.net/ud3o79ag/1/使用Knockout進行Observable更改後可見綁定不會更新
HTML:
<form action="#">
<input class="form-control" placeholder="Buscar…" type="search" name="q" data-bind="value: query, valueUpdate: 'keyup'" autocomplete="off">
</form>
<table class="table table-bordered table-striped">
<thead>
<tr data-bind="foreach: headers">
<th data-bind="click: $parent.sort">
<span data-bind="text: title"></span>
<span class="glyphicon glyphicon-sort-by-alphabet" data-bind="visible:active"></span>
</th>
</tr>
</thead>
<tbody data-bind="name:author, foreach:authors">
<tr>
<td data-bind="text:FirstName"></td>
<td data-bind="text:LastName"></td>
<td data-bind="text:Biography"></td>
<td></td>
</tr>
</tbody>
</table>
JS /淘汰賽:
var viewModel = function()
{
var self = this;
self.query = ko.observable('');
self.headers = [
{title:'First Name',sortPropertyName:'FirstName', asc: true, active: ko.observable(false)},
{title:'Last Name',sortPropertyName:'LastName', asc: true, active: ko.observable(false)},
{title:'Biography',sortPropertyName:'Biography', asc: true, active: ko.observable(false)},
{title:'Actions',sortPropertyName:'', asc: true, active: ko.observable(false)}
];
self.activeSort = ko.observable(function(){return 0;});
self.sort = function(header,event)
{
//if this header was just clicked a second time
if(header.active) {
header.asc = !header.asc; //toggle the direction of the sort
}
//make sure all other headers are set to inactive
ko.utils.arrayForEach(self.headers, function(item){ item.active = false; });
//the header that was just clicked is now active
header.active = true;//our now-active header
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;
//store the new active sort function
self.activeSort(sortFunc);
};
self.authors = ko.computed(function() {
var search = self.query().toLowerCase();
var result;
var arrayresult;
if (!search)
{
result = authors;
}
else
{
result = ko.utils.arrayFilter(authors, function(item) {
if (item['FirstName'].toLowerCase().indexOf(search) >= 0 || item.LastName.toLowerCase().indexOf(search) >= 0)
{
return true;
}
else
{
return false;
}
});
}
arrayresult = [].slice.call(result).sort(self.activeSort());
return arrayresult;
});
};
ko.applyBindings(new viewModel);
是的!完美工作!謝謝! –
「您必須使用函數設置觀察值」。我們不應該忘記這一說法。 +1爲它 –
是的,這就是我所說的「淘汰稅」... – Jeroen