How can I add paging with KnockoutJS?
My current code is:
//assuming jsondata is a collection of data correctly passed into this function
myns.DisplayFi
The basic idea is that you have a dependentObservable Computed Observables that represents the rows in your current page and bind your table to it. You would slice the overall array to get the rows for the page. Then, you have pager buttons/links that manipulate the page index, which causes the dependentObservable to be re-evaluated resulting in the current rows.
Based on your code, something like:
var myns = {};
myns.DisplayFields = function(jsondata) {
var viewModel = {
fields: ko.observableArray(jsondata),
sortByName: function() { //plus any custom functions I would like to perform
this.items.sort(function(a, b) {
return a.Name < b.Name ? -1 : 1;
});
},
pageSize: ko.observable(10),
pageIndex: ko.observable(0),
previousPage: function() {
this.pageIndex(this.pageIndex() - 1);
},
nextPage: function() {
this.pageIndex(this.pageIndex() + 1);
}
};
viewModel.maxPageIndex = ko.dependentObservable(function() {
return Math.ceil(this.fields().length / this.pageSize()) - 1;
}, viewModel);
viewModel.pagedRows = ko.dependentObservable(function() {
var size = this.pageSize();
var start = this.pageIndex() * size;
return this.fields.slice(start, start + size);
}, viewModel);
ko.applyBindings(viewModel);
};
So, you would bind your table to pagedRows
.
Sample here: http://jsfiddle.net/rniemeyer/5Xr2X/