【问题标题】:Backbone's fetch(): Add only models that are new to the collectionBackbone 的 fetch():只添加集合中的新模型
【发布时间】:2012-09-21 04:13:38
【问题描述】:

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

问题: 除了从集合中删除所有现有模型(例如id=1,2,3,4)并插入新获取的模型(id=1,2,3,5)之外,是否可以执行以下 2 个操作:

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

  2. 添加新模型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


【解决方案1】:

restful API 没有与之对话的客户端的状态概念,因此当发出GET 请求以检索对象列表(例如http://example.com/restapi/user/)时,rest 服务器应始终返回完整的对象列表匹配对象。

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

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

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

如果您正在寻找一种方法来防止修改集合中的本地项目,那将需要类似于您上面所说的巫术。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-18
    • 1970-01-01
    • 1970-01-01
    • 2013-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多