Building pagination controls with Knockout.JS

2019-04-14 12:26发布

I've inherited a project which uses Knockout.JS to render a listing of posts. The client has asked that this listing be paginated and I'm wondering if this is possible and appropriate using Knockout.JS. I could easily achieve this in pure JavaScript but I'd like to use Knockout (if appropriate) for consistency.

From what I can tell, the page uses a Native Template in the HTML of the page. There is a ViweModel which stores the posts in a ko.ObservableArray() and a post model.

The data is loaded via a jQuery ajax call where the returned JSON is mapped to post model objects and then passed into the ObservableArray which takes care of the databinding.

Is it possible to amend the ViewModel to bind pagination links (including "previous" and "next" links when required) or would I be better off writing this in plain JS?

3条回答
戒情不戒烟
2楼-- · 2019-04-14 12:56

It should be easy enough to build a computed observable in knockout that shows a "window" of the full pagelist. For example add to the view model:

this.pageIndex = ko.observable(1);
this.pagedList = ko.computed(function() {
   var startIndex = (this.pageIndex()-1) * PAGE_SIZE;
   var endIndex = startIndex + PAGE_SIZE;
   return this.fullList().slice(startIndex, endIndex);
}, this);

Then bind the "foreach" binding showing the record to pagedList instead of the full list, and in the forward and back links, simply change the value of pageIndex. Starting from there, you should be able to make it more robust/provide more functionality.

Also, this assumes you preload all data to the client anyway. It's also possible to make JSON calls on the previous and next link and update the model with the returned items. The "next" function (to be added to the view model prototype), could look like this:

ViewModel.prototype.next = function() {
   var self = this;
   this.pageIndex(this.pageIndex()+1);
   $.ajax("dataurl/page/" + this.pageIndex(), {
       success: function(data) {
          self.dataList(data);
       }
   });
}

(using jQuery syntax for the ajax call for brevity, but any method is fine)

查看更多
做个烂人
3楼-- · 2019-04-14 12:59

Writing features in KO always tend to generate less code and cleaner code than doing the same in "plain JS", jQuery or similar. So go for it!

I implemented a combobox with paging like this

https://github.com/AndersMalmgren/Knockout.Combobox/blob/master/src/knockout.combobox.js#L229

查看更多
叛逆
4楼-- · 2019-04-14 13:07

In my blog post, I have explained in very detail how to do it. you can find it (here. http://contractnamespace.blogspot.com/2014/02/pagination-with-knockout-jquery.html). It's very easy to implement and you can do it with a simple JQuery plugin.

Basically, I have used normal knockout data binding with AJAX and after data has been retrieved from the server, I call the plugin. You can find the plugin here. its called Simple Pagination.

查看更多
登录 后发表回答