【问题标题】:KnockoutJS - can't use "Slice" with ko.computed objectKnockoutJS - 不能将“切片”与 ko.computed 对象一起使用
【发布时间】:2012-09-24 20:55:36
【问题描述】:

我正在尝试使用 knockoutjs-2.1.0 创建分页,但出现以下错误:

Uncaught TypeError: Object function h(){if(0return i||e(),a.U.La(h),k} has no method 'slice'

我已将问题缩小到这一点:显然淘汰赛不喜欢在使用 ko.computed 创建的对象上调用“切片”方法。我的计算类型是这样的:

this.contactsToShow = ko.computed(function() {
// Represents a filtered list of contacts
// i.e., only those matching the "typeToShow" condition
var desiredType = this.typeToShow();
if (desiredType == "all") {
return this.allContacts();
}
return ko.utils.arrayFilter(this.allContacts(), function(aContact) {
return aContact.contactType == desiredType;
});
}, this);

当我在此处设置“showCurrentPage”属性时会引发错误:

contactListView.showCurrentPage = ko.dependentObservable(function() {
if (this.currentPage() > this.totalPages()) {
    this.currentPage(this.totalPages() - 1);
}
var startIndex = this.pageSize() * this.currentPage();
return this.contactsToShow.slice(startIndex, startIndex + this.pageSize());
}, contactListView);

但是,如果我在设置 showCurrentPage(allContacts 数组)时使用原始 observableArray,它可以工作。

你可以在这里找到 jsfiddle:http://jsfiddle.net/mzalen/S74rJ/12/

我非常感谢任何关于这个问题的建议,因为它让我发疯。

【问题讨论】:

    标签: javascript jquery pagination knockout.js


    【解决方案1】:

    Knockout 的常见错误:this.contactsToShow 在您的示例中成为函数,您必须将其作为函数调用:

    return this.contactsToShow().slice(startIndex, startIndex + this.pageSize());
    

    【讨论】:

    • 哇。谢谢,梅泽。我不敢相信这是浪费了我 4 个小时的时间。
    猜你喜欢
    • 1970-01-01
    • 2012-03-02
    • 2012-11-26
    • 2016-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-01
    • 2015-03-12
    相关资源
    最近更新 更多