如何用Backbone.PageableCollection与自定义Express路由实现LeanCloud分页
嘿,我来帮你搞定Backbone.Paginator和你的Express API适配的问题~其实核心就两个关键点:让分页参数和你的API规则对齐,以及把服务器返回的分页数据同步到Collection的状态里,下面一步步给你拆解:
1. 配置queryParams适配你的API参数名
你的Express接口用的是page(当前页码)和per_page(每页条数)作为查询参数,但Backbone.Paginator有自己默认的参数命名规则,所以我们需要手动映射,确保它生成的请求URL和你的API匹配:
在你的UserCollection里添加queryParams属性:
queryParams: { // 映射当前页码到API的`page`参数 page: function() { return this.state.currentPage; }, // 映射每页条数到API的`per_page`参数 per_page: function() { return this.state.pageSize; }, // 禁用你不需要的默认参数(比如排序相关的) sortKey: null, order: null, directions: null }
这里用函数返回值是因为state里的分页参数会动态变化,这样每次发起请求时,都会自动取最新的currentPage和pageSize生成正确的查询字符串。
2. 在parse方法中同步服务器返回的分页信息到state
你的接口返回了pageInfo(包含总用户数、总页数、当前页),我们需要把这些数据同步到Backbone.Paginator的state里,这样分页控件(比如上/下一页按钮、总页数显示)才能正常工作。修改你的parse方法:
parse: function(response) { // 把服务器返回的分页数据同步到Collection的state中 this.state.totalRecords = response.pageInfo.userCount; this.state.totalPages = response.pageInfo.pageCount; this.state.currentPage = parseInt(response.pageInfo.currentPage, 10); // 确保是数字类型 // 返回用户数据给Collection渲染 return response.userInfo; }
这样每次请求成功后,Collection的状态就会和服务器返回的分页信息保持一致,Backbone.Paginator就能自动处理分页逻辑了。
3. 完整的UserCollection配置
把上面的配置整合起来,最终的代码应该是这样:
export var UserCollection = Backbone.PageableCollection.extend({ model: UserModel, url: '/api/users', parse: function(response) { // 同步服务器分页信息到state this.state.totalRecords = response.pageInfo.userCount; this.state.totalPages = response.pageInfo.pageCount; this.state.currentPage = parseInt(response.pageInfo.currentPage, 10); return response.userInfo; }, state: { firstPage: 1, pageSize: 30, totalPages: 0, // 初始值,会被parse方法更新 totalRecords: 0, // 初始值,会被parse方法更新 currentPage: 1 // 初始值,会被parse方法更新 }, queryParams: { page: function() { return this.state.currentPage; }, per_page: function() { return this.state.pageSize; }, sortKey: null, order: null, directions: null } });
4. 服务器端的小优化(可选但推荐)
你的Express路由里,从req.query拿到的page和per_page是字符串类型,建议转成数字并设置默认值,避免出现NaN导致的分页错误:
router.get('/', function(req, res, next) { var query = new AV.Query(usersObject); // 转成数字,默认第1页、每页30条 var pageNumber = parseInt(req.query.page, 10) || 1; var perPage = parseInt(req.query.per_page, 10) || 30; query.limit(perPage); query.skip((perPage * pageNumber) - perPage); query.count(usersObject).then((userCount) => { query.find().then(function(userData) { res.json({ userInfo: userData, pageInfo: { userCount: userCount, pageCount: Math.ceil(userCount / perPage), currentPage: pageNumber } }); }); }); });
这样配置完成后,Backbone.Paginator就能自动生成符合你API规则的请求,并且同步服务器返回的分页状态,完美解决你的分页需求~
内容的提问来源于stack exchange,提问作者Sam Evers

