I'm working on building a component for a current and future projects that handles pagination on a knockout component level. I've based the idea on the accepted answer from here. Also reference the Knockout component page here.
Here is my component thus far. I am having trouble getting Any of the data to actually display, let alone with a dynamic table heading.
ko.components.register("jPage", {
viewModel: function (params) {
var self = this;
self.Items = params.Items;
self.Keys = Object.keys(self.Items);
self.PerPage = params.PerPage;
self.Page = 1;
self.PagesTotal = Math.ceil(self.Items.length / self.PerPage);
self.ItemsVisible = ko.computed(function () {
first = (self.Page * self.PerPage) - self.PerPage;
return self.Items.slice(first, first + self.PerPage);
})
self.ChangePage = function (_page) {
if (_page < 1 || _page > self.PagesTotal) return;
this.Page(_page);
}.bind(this);
},
template:
'<div data-bind="foreach: ItemsVisible"> \
Display Table headers and data here <br>\
<span data-bind="text: $data[0]"> </span>\
</div>\
<nav aria-label="Page navigation">\
<ul class="pagination">\
<li data-bind="css:{disabled: Page <= 1} ">\
<a aria-label="Previous" data-bind="click: ChangePage( Page - 1 )">\
<span aria-hidden="true">«</span>\
</a>\
</li>\
<li><a data-bind="text: Page -2, click: ChangePage( Page - 2 ), visible: Page > 2 "> </a></li>\
<li><a data-bind="text: Page -1, click: ChangePage( Page - 1 ), visible: Page > 1 "> </a></li>\
<li class="active"><a data-bind="text: Page"> </a></li>\
<li><a data-bind="text: Page +1, click: ChangePage( Page + 1 ), visible: (PagesTotal > Page +0) "></a></li>\
<li><a data-bind="text: Page +2, click: ChangePage( Page + 2 ), visible: (PagesTotal > Page +1)"></a></li>\
<li data-bind="css: {disabled: (PagesTotal < Page )}">\
<a aria-label="Next" data-bind="click: ChangePage( Page + 1 )">\
<span aria-hidden="true">»</span>\
</a>\
</li>\
</ul>\
</nav>\
'
})
This is how the component would be called:
<div data-bind="component: { name: 'jPage', params: { Items: CustomerList(), PerPage: 25} }">
CustomerList
would look like:
[
{FirstName: "John", Email: "John@example.com"},
{FirstName: "Steve", Email: "Steve@example.com"},
{FirstName: "Jim", Email: "Jim@example.com"}
]
What variables or context am I missing to access Items
keys/values?
Extra Notes. I do not have any required form of data as I can manipulate it without consequence.