jay
jay

Reputation: 434

Knockout paging binding

Sorry if this is a really basic question but I'm in the process of learning Knockout and trying to wire up paging to my dataset.

In my code below, you will see that I am retrieving the dataset, and the page size dropdown affects the results appropriately.
And when I change the page number (#'d links in footer of table), nothing happens.
Could someone tell me what I'm missing?

function ViewModel(){
    var vm = this;

    // variables
    vm.drinks = ko.observableArray();
    vm.pageSizes = [15,25,35,50];
    vm.pageSize = ko.observable(pageSizes[0]);
    vm.currentPage = ko.observable(0);

    // computed variables
    // returns number of pages required for number of results selected
    vm.PageCount = ko.computed(function(){
        if(vm.pageSize()){
            return Math.ceil(vm.drinks().length / vm.pageSize());
        }else{
            return 1;
        }
    });

    // returns items from the array for the current page
    vm.PagedResults = ko.computed(function(){
        //return vm.drinks().slice(vm.currentPage, vm.pageSize());
        return vm.drinks().slice(vm.currentPage() * vm.pageSize(), (vm.currentPage() * vm.pageSize()) + vm.pageSize());
    });

    // returns a list of numbers for all pages
    vm.PageList = ko.computed(function(){
        if(vm.PageCount() > 1){
            return Array.apply(null, {length: vm.PageCount()}).map(Number.call, Number);
        }
    });

    // methods
    vm.ResetCurrentPage = function(){
        vm.currentPage(0);
    }

    // go to page number
    vm.GoToPage = function(page){
        vm.currentPage(page);
    }

    // populate drink list
    vm.GetDrinks = function(){
        // get data
        $(function () {
            $.ajax({
                type: "GET",
                url: 'https://mysafeinfo.com/api/data?list=alcoholicbeverages&format=json',
                dataType: "json",
                success: function (data) {
                    vm.drinks(data);
                }
            });
        });
    }

    // populate drinks
    vm.GetDrinks();
}

// apply bindings
ko.applyBindings(ViewModel);
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<div class="row">
    <div class="col-sm-3 pull-right form-horizontal">
        <label class="control-label col-sm-4">
            Results:
        </label>
        <div class="col-sm-8">
            <select data-bind="value: pageSize,
              optionsCaption: 'Page Size',
              options: pageSizes, event:{ change: ResetCurrentPage }"
                    class="form-control"></select>
        </div>
    </div>
</div>

<table class="table table-striped table-condensed">
    <thead>
        <tr>
            <th style="width: 25%">Name</th>
            <th>Category</th>
            <th style="width: 50%">Description</th>
        </tr>
    </thead>
    <tbody data-bind="foreach: PagedResults">
        <tr>
            <td data-bind="text: nm"></td>
            <td data-bind="text: cat"></td>
            <td data-bind="text: dsc"></td>
        </tr>
    </tbody>
    <tfooter>
        <tr>
            <td colspan="3">
                Current Page: <label data-bind="text: currentPage"></label><br />
                <ul data-bind="foreach: PageList" class="pagination">
                    <li class="page-item"><a class="page-link" href="#" data-bind="text: $data + 1, click: GoToPage">1</a></li>
                </ul>
            </td>
        </tr>
    </tfooter>
</table>

Upvotes: 1

Views: 2181

Answers (2)

Hakan Fıstık
Hakan Fıstık

Reputation: 19511

Stack overflow is about giving solution to common problems, and the answer solution is valid for OP ,but it is not very re-usable for other cases, Here is re-usable solution to this common problem (Knockout paging)


I am working on website, which has a lot of tables (most of them need paging), so actually I needed some reusable-component for paging to use it in all the cases which I need paging.
So I developed my own component of the this issue, here it is.

Now on Github

JsFiddle

And for more details, continue reading

JavaScript

function PagingVM(options) {
    var self = this;

    self.PageSize = ko.observable(options.pageSize);
    self.CurrentPage = ko.observable(1);
    self.TotalCount = ko.observable(options.totalCount);

    self.PageCount = ko.pureComputed(function () {
        return Math.ceil(self.TotalCount() / self.PageSize());
    });

    self.SetCurrentPage = function (page) {
        if (page < self.FirstPage)
            page = self.FirstPage;

        if (page > self.LastPage())
            page = self.LastPage();

        self.CurrentPage(page);
    };

    self.FirstPage = 1;
    self.LastPage = ko.pureComputed(function () {
        return self.PageCount();
    });

    self.NextPage = ko.pureComputed(function () {
        var next = self.CurrentPage() + 1;
        if (next > self.LastPage())
            return null;
        return next;
    });

    self.PreviousPage = ko.pureComputed(function () {
        var previous = self.CurrentPage() - 1;
        if (previous < self.FirstPage)
            return null;
        return previous;
    });

    self.NeedPaging = ko.pureComputed(function () {
        return self.PageCount() > 1;
    });

    self.NextPageActive = ko.pureComputed(function () {
        return self.NextPage() != null;
    });

    self.PreviousPageActive = ko.pureComputed(function () {
        return self.PreviousPage() != null;
    });

    self.LastPageActive = ko.pureComputed(function () {
        return (self.LastPage() != self.CurrentPage());
    });

    self.FirstPageActive = ko.pureComputed(function () {
        return (self.FirstPage != self.CurrentPage());
    });

    // this should be odd number always
    var maxPageCount = 7;

    self.generateAllPages = function () {
        var pages = [];
        for (var i = self.FirstPage; i <= self.LastPage() ; i++)
            pages.push(i);

        return pages;
    };

    self.generateMaxPage = function () {
        var current = self.CurrentPage();
        var pageCount = self.PageCount();
        var first = self.FirstPage;

        var upperLimit = current + parseInt((maxPageCount - 1) / 2);
        var downLimit = current - parseInt((maxPageCount - 1) / 2);

        while (upperLimit > pageCount) {
            upperLimit--;
            if (downLimit > first)
                downLimit--;
        }

        while (downLimit < first) {
            downLimit++;
            if (upperLimit < pageCount)
                upperLimit++;
        }

        var pages = [];
        for (var i = downLimit; i <= upperLimit; i++) {
            pages.push(i);
        }
        return pages;
    };

    self.GetPages = ko.pureComputed(function () {
        self.CurrentPage();
        self.TotalCount();

        if (self.PageCount() <= maxPageCount) {
            return ko.observableArray(self.generateAllPages());
        } else {
            return ko.observableArray(self.generateMaxPage());
        }
    });

    self.Update = function (e) {
        self.TotalCount(e.TotalCount);
        self.PageSize(e.PageSize);
        self.SetCurrentPage(e.CurrentPage);
    };

    self.GoToPage = function (page) {
        if (page >= self.FirstPage && page <= self.LastPage())
            self.SetCurrentPage(page);
    }

    self.GoToFirst = function () {
        self.SetCurrentPage(self.FirstPage);
    };

    self.GoToPrevious = function () {
        var previous = self.PreviousPage();
        if (previous != null)
            self.SetCurrentPage(previous);
    };

    self.GoToNext = function () {
        var next = self.NextPage();
        if (next != null)
            self.SetCurrentPage(next);
    };

    self.GoToLast = function () {
        self.SetCurrentPage(self.LastPage());
    };
}

HTML

<ul data-bind="visible: NeedPaging" class="pagination pagination-sm">
    <li data-bind="css: { disabled: !FirstPageActive() }">
        <a data-bind="click: GoToFirst">First</a>
    </li>
    <li data-bind="css: { disabled: !PreviousPageActive() }">
        <a data-bind="click: GoToPrevious">Previous</a>
    </li>

    <!-- ko foreach: GetPages() -->
    <li data-bind="css: { active: $parent.CurrentPage() === $data }">
        <a data-bind="click: $parent.GoToPage, text: $data"></a>
    </li>
    <!-- /ko -->

    <li data-bind="css: { disabled: !NextPageActive() }">
        <a data-bind="click: GoToNext">Next</a>
    </li>
    <li data-bind="css: { disabled: !LastPageActive() }">
        <a data-bind="click: GoToLast">Last</a>
    </li>
</ul>

Features

  1. Show on need
    When there is no need for paging at all (for example the items which need to display less than the page size) then the HTML component will disappear.
    This will be established by statement data-bind="visible: NeedPaging".

  2. Disable on need
    for example, if you are already selected the last page, why the last page or the Next button should be available to press?
    I am handling this and in that case I am disabling those buttons by applying the following binding data-bind="css: { disabled: !PreviousPageActive() }"

  3. Distinguish the Selected page
    a special class (in this case called active class) is applied on the selected page, to make the user know in which page he/she is right now.
    This is established by the binding data-bind="css: { active: $parent.CurrentPage() === $data }"

  4. Last & First
    going to the first and last page is also available by simple buttons dedicated to this.

  5. Limits for displayed buttons
    suppose you have a lot of pages, for example 1000 pages, then what will happened? would you display them all for the user ? absolutely not you have to display just a few of them according to the current page. for example showing 3 pages before the page page and other 3 pages after the selected page.
    This case has been handled here <!-- ko foreach: GetPages() -->
    the GetPages function applying a simple algorithm to determine if we need to show all the pages (the page count is under the threshold, which could be determined easily), or to show just some of the buttons.
    you can determine the threshold by changing the value of the maxPageCount variable
    Right now I assigned it as the following var maxPageCount = 7; which mean that no more than 7 buttons could be displayed for the user (3 before the SelectedPage, and 3 after the Selected Page) and the Selected Page itself.

    You may wonder, what if there was not enough pages after OR before the current page to display? do not worry I am handling this in the algorithm
    for example, if you have 11 pages and you have maxPageCount = 7 and the current selected page is 10, Then the following pages will be shown

    5,6,7,8,9,10(selected page),11

    so we always stratifying the maxPageCount, in the previous example showing 5 pages before the selected page and just 1 page after the selected page.

  6. Selected Page Validation
    All set operation for the CurrentPage observable which determine the selected page by the user, is go through the function SetCurrentPage. In only this function we set this observable, and as you can see from the code, before setting the value we make validation operations to make sure that we will not go beyond the available page of the pages.

  7. Already clean
    I use only pureComputed not computed properties, which means you do not need to bother yourself with cleaning and disposing those properties. Although ,as you will see in example below, you need to dispose some other subscriptions which are outside of the component itself

NOTE 1
You may noticed that I am using some bootstrap classes in this component, This is suitable for me, but of course you can use your own classes instead of the bootstrap classes.
The bootstrap classes which I used here are pagination, pagination-sm, active and disabled
Feel free to change them as you need.

NOTE 2
So I introduced the component for you, It is time to see how it could work.
You would integrate this component in your main ViewModel as like this.

function MainVM() {
    var self = this;

    self.PagingComponent = ko.observable(new Paging({
        pageSize: 10,      // how many items you would show in one page
        totalCount: 100,   // how many ALL the items do you have.
    }));

    self.currentPageSubscription = self.PagingComponent().CurrentPage.subscribe(function (newPage) {
        // here is the code which will be executed when the user change the page.
        // you can handle this in the way you need.
        // for example, in my case, I am requesting the data from the server again by making an ajax request
        // and then updating the component

        var data = /*bring data from server , for example*/
        self.PagingComponent().Update({

            // we need to set this again, why? because we could apply some other search criteria in the bringing data from the server, 
            // so the total count of all the items could change, and this will affect the paging
            TotalCount: data.TotalCount,

            // in most cases we will not change the PageSize after we bring data from the server
            // but the component allow us to do that.
            PageSize: self.PagingComponent().PageSize(),

            // use this statement for now as it is, or you have to made some modifications on the 'Update' function.
            CurrentPage: self.PagingComponent().CurrentPage(),
        });
    });

    self.dispose = function () {
        // you need to dispose the manual created subscription, you have created before.
        self.currentPageSubscription.dispose();
    }
}

Last but not least, Sure do not forget to change the binding in the html component according to you special viewModel, or wrap all the component with the with binding like this

<div data-bind="with: PagingComponent()">
    <!-- put the component here -->
</div>

Cheers

Upvotes: 0

jay
jay

Reputation: 434

Thanks to f_martinez for helping with my issue, here is the working example if anyone ends up here looking for how to do paging. jsfiddle

I will keep this open for now in case f_martinez would like to post an answer to accept.

function ViewModel() {
  var vm = this;

  // variables  
  vm.drinks = ko.observableArray();
  vm.pageSizes = [15, 25, 35, 50];
  vm.pageSize = ko.observable(pageSizes[0]);
  vm.currentPage = ko.observable(0);

  // computed variables
  // returns number of pages required for number of results selected
  vm.PageCount = ko.computed(function() {
    if (vm.pageSize()) {
      return Math.ceil(vm.drinks().length / vm.pageSize());
    } else {
      return 1;
    }
  });

  // returns items from the array for the current page
  vm.PagedResults = ko.computed(function() {
    if (vm.PageCount() > 1) {
      //return vm.drinks().slice(vm.currentPage, vm.pageSize());
      return vm.drinks().slice(vm.currentPage() * vm.pageSize(), (vm.currentPage() * vm.pageSize()) + vm.pageSize());
    } else {
      return vm.drinks();
    }
  });

  // returns a list of numbers for all pages
  vm.PageList = ko.computed(function() {
    if (vm.PageCount() > 1) {
      return Array.apply(null, {
        length: vm.PageCount()
      }).map(Number.call, Number);
    }
  });

  // methods
  // reset to first page
  vm.ResetCurrentPage = function() {
    vm.currentPage(0);
  }

  // go to page number
  vm.GoToPage = function(page) {
    vm.currentPage(page);
  }

  // determines if page # is active returns active class
  vm.GetClass = function(page) {
    return (page == vm.currentPage()) ? "active" : "";
  }

  // populate drink list
  vm.GetDrinks = function() {
    // get data
    $(function() {
      $.ajax({
        type: "GET",
        url: 'https://mysafeinfo.com/api/data?list=alcoholicbeverages&format=json',
        dataType: "json",
        success: function(data) {
          vm.drinks(data);
        }
      });
    });
  }

  // populate drinks
  vm.GetDrinks();
}

// apply bindings
ko.applyBindings(ViewModel);
.pagination > li > a:focus,
.pagination > li > a:hover,
.pagination > li > span:focus,
.page-link.active {
  background-color: rgb(238, 238, 238);
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<div class="row">
  <div class="col-sm-3 pull-right form-horizontal">
    <label class="control-label col-sm-4">
      Results:
    </label>
    <div class="col-sm-8">
      <select data-bind="value: pageSize,           
              optionsCaption: 'All Results',
              options: pageSizes, event:{ change: ResetCurrentPage }" class="form-control"></select>
    </div>
  </div>
</div>

<table class="table table-striped table-condensed">
  <thead>
    <tr>
      <th style="width: 25%">Name</th>
      <th>Category</th>
      <th style="width: 50%">Description</th>
    </tr>
  </thead>
  <tbody data-bind="foreach: PagedResults">
    <tr>
      <td data-bind="text: nm"></td>
      <td data-bind="text: cat"></td>
      <td data-bind="text: dsc"></td>
    </tr>
  </tbody>
  <tfooter>
    <tr>
      <td colspan="3" class="text-center">
        <ul data-bind="foreach: PageList" class="pagination">
          <li class="page-item">
            <a href="#" class="page-link" data-bind="text: $data + 1, click: GoToPage, css: GetClass($data)"></a>
          </li>
        </ul>
      </td>
    </tr>
  </tfooter>
</table>

Upvotes: 2

Related Questions