Konckout pagination

by Romain Beaudoin

HTML

<script src="http://knockoutjs.com/downloads/knockout-3.0.0.js"></script>
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<table class="paginated">
    <tr>
        <th>Name</th>
        <th>Price</th>
        <th>Category</th>
        <th></th>
    </tr>
    <tbody data-bind="foreach: currentCollection">
        <tr>
            <td data-bind="text: Name"></td>
            <td data-bind="text: price"></td>
            <td data-bind="text: Category"></td>
            <td>
                <button class="btn btn-success">Edit</button>
                <button class="btn btn-danger">Delete</button>
            </td>
        </tr>
    </tbody>
</table>
<br/>
<p>current page number :
    <input data-bind="value: currentPage" />
</p>

CSS

td,th{padding:5px;}

JavaScript

var viewModel = function () {
    var self = this;

    self.pageSize = 4;
    self.currentPage = ko.observable(1);
    self.lookupCollection = ko.observableArray([]);

    self.currentCollection = ko.computed(function () {
        var startIndex = self.pageSize * (self.currentPage() - 1);
        var endIndex = startIndex + self.pageSize;
        return self.lookupCollection().slice(startIndex, endIndex);
    });
};

// create viewModel instance
var vm = new viewModel();

// 2 seconds Ajax call simulate
setTimeout(function () {

    vm.lookupCollection(dataFromAjax);

}, 2000);

// apply ko bindings
ko.applyBindings(vm);

// Mock data
var dataFromAjax = [{
        Name: 'name1',
        price: 12,
        Category: 'Cat1'
    }, {
        Name: 'name2',
        price: 5,
        Category: 'Cat2'
    }, {
        Name: 'name3',
        price: 8,
        Category: 'Cat2'
    }, {
        Name: 'name4',
        price: 2,
        Category: 'Cat2'
    }, {
        Name: 'name5',
        price: 11,
        Category: 'Cat2'
    }, {
        Name: 'name6',
        price: 44,
        Category: 'Cat2'
    }, {
        Name: 'name7',
        price: 38,
        Category: 'Cat2'
    }, {
        Name: 'name8',
        price: 14,
        Category: 'Cat2'
    }, {
        Name: 'name9',
        price: 23,
        Category: 'Cat2'
    }, {
        Name: 'name10',
        price: 18,
        Category: 'Cat2'
    }, ];