How can I add paging with KnockoutJS?
My current code is:
//assuming jsondata is a collection of data correctly passed into this function
myns.DisplayFields = function(jsondata) {
console.debug(jsondata);
window.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;
});
},
};
ko.applyBindings(viewModel);
}
My view:
<table>
<tbody data-bind='template: "fieldTemplate"'></tbody>
</table>
<script type="text/html" id="fieldTemplate">
{{each fields}}
<tr>
<td> ${ FieldId }</td>
<td>${ Type }</td>
<td><b>${ Name }</b>: ${ Description }</td>
</tr>
{{/each}}
</script>
Could or would I use jQuery, jQuery UI or another library?
I have seen on the KnockoutJS site as an example:
myModel.gridViewModel = new ko.simpleGrid.viewModel({
data: myModel.items,
columns: [
{ headerText: "Item Name", rowText: "name" },
{ headerText: "Sales Count", rowText: "sales" },
{ headerText: "Price", rowText: function (item) { return "$" + item.price.toFixed(2) } }
],
pageSize: 4
});
However where would I add pageSize to my code? How is this pageSize internally being run?
The basic idea is that you have a
dependentObservableComputed 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:
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: