jQuery Tablesorter与Knockout - 添加行

5

我尝试使用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: {}
        });

我有一个选择列表,其中包含一些值。当这个列表改变时,我会从服务器获取新的值并重新填充表格。但是旧的值仍然存在,我想要“清空”表格并重新开始。


你有现成的演示可以分享吗? - Mottie
很不幸,它不是一个公共系统,不过我会看看能否提供更多的代码。 - ruffen
1个回答

2
我找到了一个答案,但不是我想要的答案。
基本上,由于我正在使用knockout,所以不应该对视图本身进行更改,而应该更改视图模型。因此,我看了一下如何对数组进行排序,并让knockout完成其余的魔术操作。
我首先删除了所有tablesorter的痕迹(除了表格上的css类,因为我已经在样式表中使用了它)。
然后我添加了这个方法:
            self.sortContents = function (element, sortProperty) {
                var elem = $(element);
                var direction = (elem.hasClass('headerSortDown')) ? 'headerSortUp' : 'headerSortDown';
                var selector = $.trim($(element).attr('class').replace('header', '').replace('headerSortUp', '').replace('headerSortDown', ''));
                if (direction == 'headerSortUp') {
                    self.filterStorage.updateSortFilter(selector, sortProperty);
                    self.contents.sort(function(left, right) {
                        return left[sortProperty] == right[sortProperty] ? 0 : (left[sortProperty] > right[sortProperty] ? -1 : 1);
                    });
                    elem.removeClass('headerSortDown');
                    elem.addClass('headerSortUp');
                } else {
                    self.filterStorage.updateSortFilter(selector, sortProperty);
                    self.contents.sort(function (left, right) {
                        return left[sortProperty] == right[sortProperty] ? 0 : (left[sortProperty] < right[sortProperty] ? -1 : 1);
                    });
                    elem.removeClass('headerSortUp');
                    elem.addClass('headerSortDown');
                }
            };

请注意,我使用了与tablesort插件相同的CSS类,这是因为该应用程序中其他地方已经使用了tablesorter,并且这些类的CSS已经存在。

我将表头更改为以下内容:

<th class="title header" data-bind="click: function(data, event){ return sortContents($(event.target), 'contentName')}"><%: AdminResources.ContentOverview_Title %></th>

因为我陷入了这个困境,试图保存排序状态,所以我得想出一些方法。于是我创建了一个新的类,其中包括两种方法:更新(update)和获取(get)。通过这个类,我可以保存正在排序的头标题和方向。

function getSortFilter() {
    var cookie = $.cookie(tableSortedByCookie);
    return JSON.parse(cookie);
}
function updateSortFilter(selector, property) {
    $.cookie(tableSortedByCookie, null);
    $.cookie(tableSortedByCookie, JSON.stringify({ selector: selector, property: property }), { path: '/' });
}

您可以在sortcontents方法中看到update的用法(该方法位于包含表格的页面的视图模型中)。

然后我将其添加到ajax成功方法的底部:

var tableSortCookie = self.filterStorage.getSortFilter();
if (tableSortCookie != null && tableSortCookie.selector != null) {
   var header = $('.tablesorterTranslation th.' + tableSortCookie.selector);
   self.sortContents(header, tableSortCookie.property);
}

然后,我可以使用knockout来对数据进行排序,同时在更改数据、刷新页面时存储状态并加载状态。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接