Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KnockoutJS - can't use "Slice" with ko.computed object

I'm trying to create pagination using knockoutjs-2.1.0, and I'm getting the following error:

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

I've narrowed the problem down to this: Apparently knockout doesn't like calling the "slice" method on an object which is created using ko.computed. My computed type is this:

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);

And it throws an error in when I'm setting the "showCurrentPage" property, here:

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);

However, if I use the original observableArray when setting showCurrentPage (the allContacts array), it works.

You can find the jsfiddle here: http://jsfiddle.net/mzalen/S74rJ/12/

I would really appreciate any advice on this issue, as it's driving me mad.

like image 472
MattyZ Avatar asked Jul 10 '26 19:07

MattyZ


1 Answers

Common error with Knockout: this.contactsToShow becomes a function in your example and you must call it as a function:

return this.contactsToShow().slice(startIndex, startIndex + this.pageSize());
like image 70
meze Avatar answered Jul 13 '26 11:07

meze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!