在我的 Backbone 项目中,我通过以下模型获取项目集合:
MyApp.models.Items = Backbone.Model.extend({
url: "getItems"
});
然后是:
var model = new MyApp.models.Items();
model.fetch().then(function(data){
// do something here with fetched data
});
此实现工作正常,但我遇到了一种情况,我在主页上获取了所有项目,而在其他页面上只获取了 3 个项目。
我觉得如果我获取所有 Items,然后使用上述模型将其限制为 3
Items,那就太过分了。
如何使用同一模型获得有限数量的元素或全部元素?
PS:我是 Backbone 新手。
最佳答案
Backbone 集合(文档:http://backbonejs.org/#Collection)是一组模型。
当您处理用于填充 UI 组件(如数据网格/表格、数据列表等)的数据(如果您需要一组数据)时,最好使用 Backbone 集合。
MyApp.collections.ItemCollection = Backbone.Collection.extend({
model: Item,
url: "getItems"
});
集合内的模型属性指定集合中存在的数据类型。该集合使用此信息来有效管理其中的数据(在服务器获取现有模型期间进行合并/可以将原始 json 数据传递给 add 等方法)。
使用集合获取方法( http://backbonejs.org/#Collection-fetch ),从服务器获取数据。
var itemCollection = new MyApp.collections.ItemCollection();
itemCollection.fetch({
// The data property is used to send input data to the server method.
// Any data that will be required by the server method can be passed using this.
data: {
limit : 5
},
success : function(collection, response, options) {
//Do your logic
console.log("Success...");
}
error: function(collection, response, options) {
//Do your logic
}
});
关于javascript - 获得相同的元素集合,但具有不同的限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29295730/