【发布时间】:2012-09-29 18:27:00
【问题描述】:
您好,我有一个 Collection,它使用 fetch() 从 API 进行初始提取。在用户交互时,触发了第二次提取,但我没有使用原始的fetch(),而是使用了我自己定义的fetchNew():
收藏
ListingCollection = Backbone.Collection.extend({
model: Listing,
url: '/api/search_by_bounds',
fetchNew: function(options) {
options = options || {};
var collection = this,
success = options.success;
options.success = function(resp, status, xhr) {
_(collection.parse(resp, xhr)).each(function(item) {
// added this conditional block
if (!collection.get(item.id)) {
// Update collection
collection.add(item, {silent:true});
// Render View
new ListingMarkerView({ model:item }).render();
}
});
if (!options.silent) {
collection.trigger('reset', collection, options);
}
if (success) success(collection, resp);
};
return (this.sync || Backbone.sync).call(this, 'read', this, options);
}
});
这只会将新模型添加到集合中,并仅渲染这些新模型的视图。 (如果所有的View都被移除并重新渲染,会导致闪烁)
查看
ListingMarkerView = Backbone.View.extend({
render: function() {
var marker = L.marker([this.model.get('lat'), this.model.get('lng')]);
markers.addLayer(marker);
},
close: function() {
this.unbind;
}
});
错误
但是我得到一个错误:
Uncaught TypeError: Object #<Object> has no method 'get'
对应ListingMarkerView中的这一行
var marker = L.marker([this.model.get('lat'), this.model.get('lng')]);
调试
如果我要在呈现ListingMarkerView 的行之前放置一个console.log(item)
console.log(item)
new ListingMarkerView({ model:item }).render();
我确实看到了一个有效的item:
Object
id: "2599084"
lat: "42.276852"
lng: "-71.165421"
price: "2850"
__proto__: Object
所以...
问题
似乎是什么问题?如何解决?谢谢!
【问题讨论】:
-
我宁愿用平常的
.reset,你为什么要这样做?您可以发布工作站点的链接以便我进行检查吗? -
.reset是否会删除初始fetch()中但未在后续调用中的项目?我希望只是将新模型添加到集合中而不删除旧模型。 -
如果您想添加新的而不删除旧的,请使用
fetch({add:true})。但是,您仍然应该理解我对您的问题给出的答案,因为它肯定会在其他地方出现。 -
是的
fetch{add:true})有我想要的效果,谢谢!但是,使用_.bindAll后我仍然无法渲染视图 -
再次:您能否发布工作站点的链接以便我进行检查?
标签: javascript jquery backbone.js