Backbone:保持两个集合同步

时间:2013-05-11 15:55:50

标签: javascript backbone.js underscore.js backbone-events

我有一组瓷砖。当应用程序启动时,将从服务器获取集合,并将其克隆分配给collection对象的MdApp.TilesCollection属性:

MdApp.TilesCollection.fetch({
        success: function(){
            console.log('Tiles collection fetched from server');
            console.log(MdApp.TilesCollection);
            if(!MdApp.TilesCollection.collection){
                MdApp.TilesCollection.collection = new Backbone.Collection(MdApp.TilesCollection.models);
                console.log('Made copy of collection in fetched collection instance');
            }
        },
        error: function(){
            console.log('Error!Unable to fetch tiles collection from server');
        }
    });

这样做是为了过滤目的:

    TilesCollection = Backbone.Collection.extend({

    model: MdApp.TileModel,

    url : 'api/',

    rewriteModel: function(model){
        this.set(model);
    },

    byPrivate : function(){
        var filtered = this.collection.filter(function(tile){
            return tile.get('private') == '1';
        });
        console.log('filtered private: ' + filtered);
        return filtered;
    },

    byPublic : function(){
        var filtered = this.collection.filter(function(tile){
            return tile.get('private') == '0';
        });
        console.log('filtered public: ' + filtered);
        return filtered;
    },

    byFavourite: function(){
        var filtered = this.collection.filter(function(tile){
            return tile.get('favourite') == '1';
        });
        console.log('filtered favourite: ' + filtered);
        return filtered;
    },

    byAsc : function(){
        var filtered = this.collection.sortBy(function(tile){
            return tile.get('id');
        });
        console.log('filtered ascending: ' + filtered);
        return filtered;
    },

    byDesc : function(){
        var filtered = this.collection.sortBy(function(tile){
            return -tile.get('id');
        });
        console.log('filtered descending: ' + filtered);
        return filtered;
    },

    refilter: function(){
        console.log(this.collection);
        return this.collection.models;
    }
});

我想要做的是让MdApp.TilesCollectionMdApp.TilesCollection.collection保持同步。添加或修改MdApp.TilesCollection模型时,我想对其克隆进行特定更改。当然,我可以在每次更改内容时创建新的集合并将其分配给该属性,但是当集合非常大时,它可能非常低效。有没有人可以放弃任何提示或解决方案?

1 个答案:

答案 0 :(得分:0)

您不需要保留集合的克隆以进行过滤,您可以对原始集合执行这些过滤操作。

byPrivate : function(){
    var filtered = this.where({ private: 1 });
    console.log('filtered private: ' + filtered);
    return filtered;
}

如果出于某种原因,您仍然希望保留克隆并同步它,而不是在获取成功回调中创建新集合,您只需reset就像这样:

MdApp.TilesCollection.collection.reset(MdApp.TilesCollection.models);