使用Knockout.JS构建分页控件 [英] Building pagination controls with Knockout.JS

查看:145
本文介绍了使用Knockout.JS构建分页控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我继承了一个使用Knockout.JS来呈现帖子列表的项目。客户已经要求对此列表进行分页,我想知道这是否可行且适当使用Knockout.JS。我可以在纯JavaScript中轻松实现这一点,但我想使用Knockout(如果适用)来保持一致性。

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.

据我所知,该页面在页面的HTML中使用原生模板。有一个ViweModel将帖子存储在 ko.ObservableArray()和一个帖子模型中。

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.

数据通过jQuery ajax调用加载,其中返回的JSON映射到post模型对象,然后传递给ObservableArray,它负责数据绑定。

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.

是否可以修改ViewModel绑定分页链接(包括需要时的上一个和下一个链接)还是我最好用普通的JS写这个?

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?

推荐答案

在knockout中构建一个计算的observable应该很容易,它显示了整个页面列表的窗口。例如,添加到视图模型:

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);

然后将显示记录的foreach绑定绑定到 pagedList 而不是完整列表,以及前进和后退链接,只需更改 pageIndex 的值即可。从那里开始,您应该能够使其更强大/提供更多功能。

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.

此外,这假设您无论如何都要将所有数据预加载到客户端。也可以在上一个和下一个链接上进行JSON调用,并使用返回的项目更新模型。 下一个函数(将添加到视图模型原型中)可能如下所示:

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);
       }
   });
}

(为简洁起见,使用jQuery语法进行ajax调用,但任何方法都没问题)

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

这篇关于使用Knockout.JS构建分页控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆