我的服务器端 API 遵循经典的结果分页模型,例如
/api/transactions/=> 第 1 页(默认限制 10 项) /api/transactions/?p=2 => 第 2 页
我想构建一个带有 Backbone View 的无限滚动系统。
我已经有了非分页集合+ View 设置。父 View 如下所示:
Backbone.View.extend({
initialize: function() {
this.collection = TransactionCollection;
this.fetch();
this.listenTo( this.collection, 'reset', this.renderEntries );
this.listenTo( this.collection, 'add', this.fetch );
this.rowViews = [];
this.render();
},
fetch: function() {
this.collection.fetch({ reset:true });
},
render: function() {
this.$el.html( template() );
this.renderEntries();
return this;
},
renderEntries: function() {
this.clearEntryRows();
this.collection.each(function(item) {
var row = new TransactionItemView( item );
this.rowViews.push( row );
this.$el.find('.entry-list').append( row.render().el );
}, this);
},
clearEntryRows: function() {
this.rowViews.forEach(function(v) {
if (v.close) v.close();
});
this.rowViews = [];
},
// ...
}
这是 View 代码的相关部分( subview 是简单的项目 View ,使用模板呈现自身)。
该集合仍然非常基本:
var TransactionCollection = Backbone.Collection.extend({
model: Transaction,
url: '/api/transactions'
});
现在是时候添加分页了。我想我将在每次 renderEntries() 调用之后添加一个按钮“更多...”。该按钮将获取下一页(无需重置集合)并调用另一个 renderEntries。 this.clearEntryRows() 将被移至重置回调。
我的问题是:如何获取第二页并添加模型而不重置集合并仅拦截该事件以呈现下一个条目页面? 我读过一些关于“同步”事件的内容:根据我的理解,只有当我使用 Reset:true 获取时才会触发“重置”,无论如何,每次获取集合时都会触发“同步”。
因此,如果这是正确的,我只能在重置事件时清除条目行并同步显示行。但是我怎样才能只显示列表中新添加的(例如第 2 页)行呢?
我有点困惑。
最佳答案
this.collection.fetch({ add: true, remove: false, merge: false, data: {p: 2} });
这允许您使用指定的获取参数进行获取,并且仅将不存在的条目添加到集合中。
您认为:
initialize: function () {
this.listenTo(this.collection, 'add', handlerForRenderingNewEntries);
}
要仅渲染新模型,您可以使用指定的属性返回它们,例如额外的属性“page”。按此属性过滤它们并将其发送到渲染器。
关于javascript - 简单的Backbone.js集合无限分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25908288/