collection.reset 未填充所有模型
collection.reset not populating with all the models
我的 Backbone collection 调用这样的提取
collection.fetch({data : {product_type: foo, year: bar}, processData: true, success: function(response){
console.log(response, "response from server");
collection.reset(response);
}});
在Chrome控制台中,显示数组有6条记录,但当我进一步检查响应时,数组中实际上有0个模型。您可以通过注意第一行中的数字 6 和最后一行中的 Array[0] 来看到这一点:
MyCollection {length: 6, models: Array[6], _byId: Object, sortField: "date", sortDirection: "DESC"…}
_byId: Object
_events: Object
_listenId: "l1"
length: 0
model: function (attrs, options) {
models: Array[0]
//...other details ommitted...//
此外,我的 6 个预期模型中只有 1 个出现在视图中。鉴于以上,我认为可能会出现 0 或 6,但有 1.
为什么 collection 没有对所有 6 个模型进行重置?
根据文档 Collection#fetch 我可以看到 success
回调有 3 个参数
(collection, response, options)
所以在你的情况下 response
是一个 collection
根据来自服务器的 JSON
数组更新,所以你不需要再次重置它,而是用集合意味着您添加清除集合并添加实际上是集合本身的新模型。所以你可以改用
collection.reset(response.models)
但我认为您不应该在 success
回调中对集合执行任何操作,backbone 会自动为您完成。
我的 Backbone collection 调用这样的提取
collection.fetch({data : {product_type: foo, year: bar}, processData: true, success: function(response){
console.log(response, "response from server");
collection.reset(response);
}});
在Chrome控制台中,显示数组有6条记录,但当我进一步检查响应时,数组中实际上有0个模型。您可以通过注意第一行中的数字 6 和最后一行中的 Array[0] 来看到这一点:
MyCollection {length: 6, models: Array[6], _byId: Object, sortField: "date", sortDirection: "DESC"…}
_byId: Object
_events: Object
_listenId: "l1"
length: 0
model: function (attrs, options) {
models: Array[0]
//...other details ommitted...//
此外,我的 6 个预期模型中只有 1 个出现在视图中。鉴于以上,我认为可能会出现 0 或 6,但有 1.
为什么 collection 没有对所有 6 个模型进行重置?
根据文档 Collection#fetch 我可以看到 success
回调有 3 个参数
(collection, response, options)
所以在你的情况下 response
是一个 collection
根据来自服务器的 JSON
数组更新,所以你不需要再次重置它,而是用集合意味着您添加清除集合并添加实际上是集合本身的新模型。所以你可以改用
collection.reset(response.models)
但我认为您不应该在 success
回调中对集合执行任何操作,backbone 会自动为您完成。