Monday, September 29, 2014

Paged Model for Knockout.js foreach pagination

Here is a paged model which can be used with knockout.js to display paged tables etc.



1:  var Model = function() {  
2:    var self = this;  
3:    //Array container to host items  
4:    this.all = ko.observableArray([]);  
5:    //Current Page Number  
6:    this.pageNumber = ko.observable(1);  
7:    //No of Items Per page  
8:    this.nbPerPage = ko.observable(3);  
9:    //Total Number of Pages  
10:    this.totalPages = ko.computed(function() {  
11:      var div = Math.floor(self.all().length / self.nbPerPage());  
12:      div += self.all().length % self.nbPerPage() > 0 ? 1 : 0;  
13:      return div ;  
14:    });  
15:    //Number of Items in the Array  
16:    this.nItems = ko.computed(function () {  
17:      return self.all().length;  
18:    });  
19:    //Paginated array  
20:    this.paginated = ko.computed(function() {  
21:      var first = (self.pageNumber() - 1) * self.nbPerPage();  
22:      return self.all.slice(first, first + self.nbPerPage());  
23:    });  
24:    //Has a previous item  
25:    this.hasPrevious = ko.computed(function() {  
26:      return self.pageNumber() !== 1;  
27:    });  
28:    //Has a next item  
29:    this.hasNext = ko.computed(function() {  
30:      return self.pageNumber() !== self.totalPages();  
31:    });  
32:    //Move to next  
33:    this.next = function() {  
34:      if(self.pageNumber() < self.totalPages()) {  
35:        self.pageNumber(self.pageNumber() + 1);  
36:      }  
37:    }  
38:    //Move to first page  
39:    this.first = function () {    
40:        self.pageNumber(1);   
41:    }  
42:    //Move to Last page  
43:    this.last = function () {  
44:      self.pageNumber(self.totalPages());  
45:    }  
46:    //Move to Previous page  
47:    this.previous = function() {  
48:      if(self.pageNumber() != 1) {  
49:        self.pageNumber(self.pageNumber() - 1);  
50:      }  
51:    }  
52:    //set number of Items per page  
53:    this.setnPerPage = function (val) {  
54:      return function () {  
55:        self.nbPerPage(val);  
56:      }  
57:    }  
58:    //filtering options  
59:    this.filter = function (val,id) {  
60:      return function () {    
61:      //Create Own filtering  
62:    }  
63:    }  
64:  }  

Use following code to initialed and start binding.
1:   var m = new Model();  
2:        m.all(data);  
3:        m.nbPerPage(5);  
4:        ko.applyBindings(m);  
5:        $('#loading').button('reset');  

where data can be any json object.
Usage:
    1. use 'paginated' in foreach binding.
    2. load initial data to 'all'
    3. Use click bind for use 'first,next, last, previous'.