templatesmvvmknockout.jspagination

Knockout template to create pagination UI / links similar to StackOverflow


I have a functioning Knockout template for some pagination UI that works with a Knockout-based shared data grid. This template renders an HREF for each "page" of data in the grid.

The template works but it's klunky because if I fetch a lot of data, then I end up with dozens and dozens of navigation page links below the grid. Here's the current template:

<div class="idTemplate_ko_simpleGrid_pageLinks">
    <p>
        <span>Go to page:</span>
        <!-- ko foreach: ko.utils.range(0, maxPageIndex) -->
            <a href="javascript:void(0);"
               class="grid-pagination" 
               data-bind="text: $data + 1, click: function() { $root.currentPageIndex($data) }, css: { selected: $data == $root.currentPageIndex() }"></a>
        <!-- /ko -->
    </p>
</div>

The 'currentPageIndex' value is just a simple ko observable in the model:

this.currentPageIndex = ko.observable(0);

And 'maxPageIndex' is a computed observable in the model:

this.maxPageIndex = ko.computed(function () {
    return Math.ceil(ko.utils.unwrapObservable(this.filteredItems()).length / this.pageSize()) - 1;
}, this);

How can I modify the template and model to enable paging UI similar to StackOverflow?

For example:

prev 1 ... 3 4 5 6 7 ... 69 next


Solution

  • This is exactly the pager style I have been using for a while now.

    I just finished extracting the pager functionality I used on several projects, into an extension to knockout and template by example.

    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. But an example working template is included.

    See the source example.html for usage.