Mike W
Mike W

Reputation: 559

Knockout js template not binding to ko.computed

I have pretty much spent most of the day playing around in complete frustration in an effort to get the attached code to work correctly. The code is more or less taken from http://jsfiddle.net/rniemeyer/5Xr2X/. My version displays the first page, IE, the first 10 rows. Clicking next fires the pagedRows function but will not for the life of me display the next page of data. Heeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeelp.

Attached is the code

<table>
   <tr>
       <th>Id</th>
       <th>Type</th>
       <th>Name</th>
    </tr>
  <tbody data-bind='template: { name: "fieldTemplate", foreach: pagedRows }'></tbody>
</table>

<a href="#" data-bind="click: previous, visible: pageIndex() > 0">Previous</a>
<a href="#" data-bind="click: next, visible: pageIndex() < maxPageIndex()">Next</a>

<script type="text/html" id="fieldTemplate">
    <tr>
         <td><span data-bind="text:FieldId" /></td>
         <td><span data-bind="text:Type" /></td>
         <td><span data-bind="text:Description" /></td>
    </tr>
</script>

<script>
    function ViewModel(jsondata) {
        var self = this;
        self.fields = ko.observableArray(jsondata);
        self.pageIndex = ko.observable(0);
        self.pageSize = ko.observable(10);

        self.pagedRows = ko.computed(function () {
            var size = self.pageSize();
            var start = self.pageIndex() * size;
            return self.fields.slice(start, start + size);
        });

        self.maxPageIndex = ko.computed(function () {
            return Math.ceil(self.fields().length / self.pageSize()) - 1;
        });

        self.next = function () {
            self.pageIndex(self.pageIndex + 1);
        }
        self.previous = function () {
            self.pageIndex(self.pageIndex - 1);
        }
    }

    $(function () {
        var data = [];
        for (var i = 0; i < 100; i++) {
            data.push({
                FieldId: i,
                Type: "Type" + i,
                Name: "Name" + i,
                Description: "Description" + i
            })
        }

        ko.applyBindings(new ViewModel(data));

    });
</script>

Seems insanely straight forward, but I am just not getting it. any help would be greatly appreciated.

thanks

Mike

Upvotes: 0

Views: 756

Answers (1)

RP Niemeyer
RP Niemeyer

Reputation: 114792

When you are doing the next/previous actions, you need to retrieve the observable's value by calling it as a function and add or subtract 1 from it. So, you would want to do:

self.next = function() {
    self.pageIndex(self.pageIndex() + 1);
}
self.previous = function() {
    self.pageIndex(self.pageIndex() - 1);
}

Upvotes: 2

Related Questions