如何获得过滤集合

时间:2012-09-29 11:03:11

标签: javascript backbone.js local-storage backbone-views

假设我有一个big collection,我想将这个大集合的一个子集用于不同的视图。

我尝试了以下代码,但它不起作用,因为filtered collection实际上是一个新代码而且它没有引用BigCollection instance

我的问题是:
如何获得一个BigCollection instance

的子集的集合

这是我的代码。请参阅评论以获取更多信息:

// bigCollection.js
var BigCollection = Backbone.Collection.extend({
    storageName: 'myCollectionStorage',
    // some code
});

// firstView.js
var firstView = Marionette.CompositeView.extend({
    initialize: function(){
        var filtered = bigCollection.where({type: 'todo'});
        this.collection = new Backbone.Collection(filtered);
        // the issue is about the fact 
        // this.collection does not refer to bigCollection
        // but it is a new one so when I save the data 
        // it does not save on localStorage.myCollectionStorage
    }
});

2 个答案:

答案 0 :(得分:1)

使用BigCollection进行过滤收集,如下所示:

    // firstView.js
    var firstView = Marionette.CompositeView.extend({
        initialize: function(){
            var filtered = bigCollection.where({type: 'todo'});
            this.collection = new BigCollection(filtered);
            // now, it will save on localStorage.myCollectionStorage
        }
    });

答案 1 :(得分:0)

您可以将原始模型保存在集合中的变量中,以便在取消应用过滤器后恢复它们,如下所示:

// bigCollection.js
var BigCollection = Backbone.Collection.extend({
    storageName: 'myCollectionStorage',
    // some code
});

// firstView.js
var firstView = Marionette.CompositeView.extend({
    initialize: function(){
        bigCollection.original_models = bigCollection.models;
        bigCollection.models = bigCollection.where({type: 'todo'});
    }
});

然后您可以在切换过滤器时恢复它们:

bigCollection.models = bigCollection.original_models;
相关问题