Backbone的fetch():仅添加集合中的新模型

时间:2012-09-29 15:58:06

标签: javascript backbone.js underscore.js

在初始fetch之后调用fetch(响应用户的操作)时,许多新获取的模型可能与最初fetch的现有模型类似。如果我使用fetch选项调用add: true,则集合中可能存在重复的模型。

问题:而不是从集合中删除所有现有模型(比如id=1,2,3,4)并插入新获取的模型(id=1,2,3,5),是否可以执行以下两项行动:

  1. 仅添加新模型id=5,从而生成包含id=1,2,3,4,5的集合。然后只渲染新视图(id=5

  2. 添加新模型id=5并删除新fetchid=4)中未找到的模型。然后渲染新视图(id=5)并删除旧视图(id=4

  3. 尝试:

    使用App.listingCollection.fetch()函数,而不是调用fetchNew()。这仅适用于将新模型id=5添加到集合中。

    如何在不重新渲染现有视图id=5的情况下触发新视图的呈现(id=1,2,3,4)?我使用new ListingMarkerView({ model:item }).render();中的行ListingCollection尝试了此操作,但在var marker = L.marker([this.model.get('lat'), this.model.get('lng')]);中回复ListingMarkerView行时收到错误:

    错误

    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;
        }
    
    });
    

1 个答案:

答案 0 :(得分:3)

一个宁静的API没有与它交谈的客户端状态的概念,因此在发出GET请求来检索对象列表(例如http://example.com/restapi/user/)时,其余服务器应该总是返回一个完整的匹配对象列表。

在Backbone端,您应该只使用服务器中的列表.reset集合。 .reset将清空集合,然后添加所有项目,例如:

my_collection.fetch({success: function(collection, resp){ 
    collection.reset(resp, {silent: true});
}});

这样你就不会发生碰撞而且你不必担心任何事情。除非您有模型,否则您已在本地集合中更改了尚未保存回服务器的模型。

如果您正在寻找一种方法来阻止修改集合中的本地商品,那就需要像上面提到的巫术一样。

相关问题