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?
Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model.
Knockout. js is a JavaScript implementation of the MVVM pattern with templates. There are several advantages of Knockout. js and its MVVM architecture design.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With