How to handle pagination with Knockout

How to handle pagination with Knockout

Asked on December 11, 2018 in knockout js.
Add Comment


  • 3 Answer(s)

      Use the Knockout for Pagination .Try  this way:

    • Have an observableArray contain all elements .
    • Have an observable containing the present page .
    • Have a variable declaring the more elements per page .
    • Have a computed that send back the number of pages, calculated thanks to the number of elements per page and the total number of elements.
    • Finally, Include a computed that slices the array having all the elements.

    Given that, Given a function that increments  or decrements  the present page.

        Here is a quick example:

    var Model = function() {
        var self = this;
        this.all = ko.observableArray([]);
        this.pageNumber = ko.observable(0);
        this.nbPerPage = 25;
        this.totalPages = ko.computed(function() {
            var div = Math.floor(self.all().length / self.nbPerPage);
            div += self.all().length % self.nbPerPage > 0 ? 1 : 0;
            return div - 1;
        });
        this.paginated = ko.computed(function() {
            var first = self.pageNumber() * self.nbPerPage;
            return self.all.slice(first, first + self.nbPerPage);
        });
        this.hasPrevious = ko.computed(function() {
            return self.pageNumber() !== 0;
        });
        this.hasNext = ko.computed(function() {
            return self.pageNumber() !== self.totalPages();
        });
        this.next = function() {
            if(self.pageNumber() < self.totalPages()) {
                self.pageNumber(self.pageNumber() + 1);
            }
        }
        this.previous = function() {
            if(self.pageNumber() != 0) {
                self.pageNumber(self.pageNumber() - 1);
            }
        }
    }
    

        Use this link : http://jsfiddle.net/LAbCv/ .

    Answered on December 11, 2018.
    Add Comment

        For making a  pagination ,A blog post is made with the help of a little JQuery plugin (here).

        Usual knockout data binding is used with AJAX and after data has been obtained from the server The plugin is used . search  the plugin here. It’s called Simple Pagination.

    Answered on December 11, 2018.
    Add Comment

    This is searches many times for “knockout pagination“, so the knockout extension knockout-paging (git) is worth mentioning.

    It give pagination by enlarge the ko.observableArray. It is well documented and easy to use.

    The usage example is here..

    Answered on December 11, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.