【发布时间】:2012-09-21 04:13:38
【问题描述】:
当在初始 fetch 之后调用 fetch(响应用户操作)时,许多新获取的模型可能与初始 fetch 中的现有模型相似。如果我使用add: true 选项调用fetch,则集合中可能存在重复的模型。
问题: 除了从集合中删除所有现有模型(例如id=1,2,3,4)并插入新获取的模型(id=1,2,3,5)之外,是否可以执行以下 2 个操作:
仅添加新模型
id=5,从而生成带有id=1,2,3,4,5的集合。然后只渲染新视图 (id=5)添加新模型
id=5并删除新fetch(id=4) 中未找到的模型。然后渲染新视图 (id=5) 并移除旧视图 (id=4)
尝试:
使用fetchNew() 函数而不是调用App.listingCollection.fetch()。这仅适用于将新模型 id=5 添加到集合中。
如何在不重新渲染现有视图id=1,2,3,4 的情况下触发仅渲染新视图 (id=5)?我在ListingCollection 中使用new ListingMarkerView({ model:item }).render(); 行尝试了此操作,但在响应ListingMarkerView 中的var marker = L.marker([this.model.get('lat'), this.model.get('lng')]); 行时出现错误:
错误
Uncaught TypeError: Object #<Object> has no method 'get'
收藏
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)) {
collection.add(item, {silent:true});
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);
}
});
查看
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;
}
});
【问题讨论】:
-
update: true做你想做的事吗? ``` App.listingCollection.fetch({update: true}); ```
标签: javascript backbone.js underscore.js