我尝试使用tablesorter和savesort widget。表格是由knockout填充的。
第一次填充表格时,我得到了正确数量的行,并且它记住了排序方式。然后,我通过ajax重新填充了表格,并将其绑定到knockout数组上。数据随之加倍,但是knockout(正确地)只跟踪了一半的数据。
到目前为止,我已经追踪到当我在这个方法中应用保存的排序方式时:
self.tablesorter = function () {
$('table.tablesorterTranslation').trigger("update");
setTimeout(function () {
var sl = $.tablesorter.storage($('table.tablesorterTranslation'), 'tablesorter-savesort');
var sortList = (sl && sl.hasOwnProperty('sortList') && $.isArray(sl.sortList)) ? sl.sortList : '';
if (sortList && sortList.length > 0) {
// update sort change
$('table.tablesorterTranslation').trigger("sorton", [sortList]);
}
}, 1000);
return false;
};
此方法由knockout postaction绑定调用。
在调用该方法之前,每个knockout数组中的项都有一个表格行,在postaction之后,我有两个表格行,一个被knockout跟踪,另一个似乎是由tablesorter添加的。
这是由于tablesorter缓存值造成的吗?是否有一种清除它的方法?
HTML:
<table class="tablesorterTranslation" data-bind="visible: contents().length > 0">
<colgroup>
<col class="referencenumber"/>
<col class="title"/>
</colgroup>
<thead>
<tr>
<th class="referencenumber">Ref number</th>
<th class="title">Title</th>
</tr>
</thead>
<tbody data-bind="foreach: contents, postAction: tablesorter(), visible: contents().length > 0">
<tr>
<td class="referencenumber">
<span data-bind="text: contentReferenceNumber"></span>
</td>
<td class="title">
<a data-bind="attr: {href: previewUrl, title: previewTitle}, click: previewpopup" class="preview_translation"><%: AdminResources.Menu_Preview %></a>
</td>
</tr>
</tbody>
</table>
重新填充表格的Ajax:
self.setContentList = function () {
if ($('#LanguageIdNameValuePairs option').length > 0) {
self.contents.removeAll();
self.loading(true);
$.ajax('<%= Url.Action("GetContentList", "TranslateContentMenu") %>',
{
dataType: 'json',
data: {
languageId: $('#LanguageIdNameValuePairs').val(),
page: self.page
},
success: function (allData) {
var mappedContent = $.map(allData, function (item) { return new ContentViewModel(item); });
self.loading(false);
self.contents(mappedContent);
}
});
} else {
self.contents(new Array());
}
};
内容视图模型:
(function (ko) {
PODIUM.translation.ContentViewModel = function(data) {
this.contentReferenceId = ko.observable(data.contentReferenceId);
this.contentName = data.contentName;
this.previewUrl = ko.observable(data.previewUrl);
this.previewTitle = ko.observable(data.previewTitle);
this.publishTitle = ko.observable(data.publishTitle);
this.contentReferenceNumber = ko.observable(data.contentReferenceNumber);
};
}(ko));
最后,填充表格并定义tablesort,使用savesort(我认为savesort是问题所在)。
$('#OptionsMenu').change(function () {
viewModel.setContentList();
});
$('table.tablesorterTranslation').tablesorter({
widgets: ["saveSort"],
widgetOptions: {}
});
我有一个选择列表,其中包含一些值。当这个列表改变时,我会从服务器获取新的值并重新填充表格。但是旧的值仍然存在,我想要“清空”表格并重新开始。