0

我有一组瓷砖。当应用程序启动时,从服务器获取集合并将其克隆分配给对象的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.TilesCollection同步MdApp.TilesCollection.collection。当MdApp.TilesCollection添加或修改 的模型时,我想对其克隆进行那些特定的更改。当然,我可以在每次更改某些内容时创建新集合并将其分配给该属性,但是当集合非常大时,它可能会非常低效。有没有人可以放弃任何提示或解决方案?

4

1 回答 1

1

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

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

如果出于某种原因您仍想保留克隆并同步它,而不是在 fetch 成功回调中创建新集合,您可以像这样简单地重置它:

MdApp.TilesCollection.collection.reset(MdApp.TilesCollection.models);
于 2013-05-11T16:54:46.417 回答