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/
Did you achieve what you wanted?
I recently pushed an example of a nice pager using knockout to github.
See https://github.com/remcoros/ko.pager for the source and http://remcoros.github.com/ko.pager/example.html for a working example.
All computations and some convenient properties are provided by the 'Pager' class, which you can create and bind to. An example working template is included.
See the source example.html for some doc and usage.
Maybe https://github.com/addyosmani/backbone.paginator is something for you? From the Github page:
Backbone.Paginator is a set of opinionated components for paginating collections of data using Backbone.js. It aims to provide both solutions for assisting with pagination of requests to a server (e.g an API) as well as pagination of single-loads of data, where we may wish to further paginate a collection of N results into M pages within a view.