我试图设置我的集合提取的限制,然后迭代它。我想取一次让4个项目。当我下次想要它获取接下来的4个项目时运行fetch。
我的收藏品看起来像这样。
define([
'Underscore',
'Backbone',
'app',
'StartModel',
], function (_, Backbone, app, StartModel) {
var StartCollection = Backbone.Collection.extend({
model: StartModel,
url: "url",
startIndex: 0,
numItems: 4,
parse: function (response) {
return response.data;
},
initialize: function() {
}
});
return StartCollection;
});
我的获取功能看起来像这样。(在视图中)
render: function(){
var self = this;
if (this.startIndex != -1) {
this.collection.fetch({
data: {
numItems: self.numItems,
startIndex: self.startIndex
},
success: function (collection, response) {
if (response.length === self.numItems){
self.startIndex = self.startIndex + self.numItems;
} else {
// if the response is less than 4 models you have reached the end of the models
self.startIndex = -1;
}
self.$el.html(self.template);
_.each(collection.models, function(model,index) {
self.$el.find(".holder").append("<p>"+model.toJSON+"</p>"())
});
}
});
}
},
这是我的模特
define([
'Underscore',
'Backbone',
'app',
], function (_, Backbone, app) {
var StartModel = Backbone.Model.extend({
defaults: function() {
return {
};
},
clear: function() {
this.destroy();
}
});
return StartModel;
});
需要一些帮助。谁知道怎么做?
答案 0 :(得分:1)
我这样做的方法是设置一个每次递增4的变量,向服务器发送一个请求,该请求带有一个标志,指示要返回的模型。您可以通过设置data
选项来完成此操作。以下是Backbone docs:
jQuery.ajax选项也可以直接作为fetch选项传递,所以 获取分页集合的特定页面: Documents.fetch({data:{page:3}})
Here is some documentation for jQuery.ajax()
将startIndex
和numItems
添加到您的收藏中:
var StartCollection = Backbone.Collection.extend({
model: StartModel,
url: "url",
startIndex: 0,
numItems: 4,
// ... more code
在您的渲染功能中,当您致电fetch
render: function(){
var self = this;
if (this.startIndex != -1) {
this.collection.fetch({
data: {
numItems: self.collection.numItems,
startIndex: self.collection.startIndex
},
success: function (collection, response) {
if (response.length === self.collection.numItems){
self.collection.startIndex = self.collection.startIndex +
self.collection.numItems;
} else {
// if the response is less than 4 models you have reached the end of the models
self.collection.startIndex = -1;
}
self.$el.html(self.template);
_.each(collection.models, function(model,index) {
self.$el.find(".holder").append(model.toJSON())
});
}
});
}
},
在服务器的控制器中,从params中抓取startIndex
和numItems
,然后使用它们将正确的模型返回到您的应用。