I’ve recently been asked about techniques for improving List performance in
HTML-based views. One of the cheapest tricks to do that is paging. Most modern
List implementations do apply it in one way or the another. Often it is hidden behind
scrolling. Here’s a simple way to do classical paging with buttons to navigate between pages using DukeScript and Knockout. First let’s create
a simple model with 1000 Strings:
We have a method for switching to a certain page if somebody clicks a link.
The trick to support dynamic paging is to add two ComputedProperties:
The first one dynamically updates the page count when elements are removed or added.
The second one gives you a sublist corresponding to the currently selected page.
In HTML you can use it like this:
The tricky part here is to create the links. Knockout only has a foreach binding
by default. The solution to this is to simply create an array with pageCount number of entries.
Now we can iterate over this array. In order to pass the index to our function we use the click binding.
And we extend it by binding the index to the call. This way we’ll receive the index in our gotoPage
That’s it, you can now run the code and you will see nice and simple dynamic paging.
In order to prove that it really is dynamic you can add a little Timer that adds new entries:
Start the timer after you’ve initialized the view model, and you’ll see how
new links appear as the new items roll in, and how the page automatically updates.