2012-09-29 33 views
1

让我们假设我有一个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 
    } 
}); 

回答

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

+1是的,你的想法很好。只有一个问题,当我从firstView创建新模型时,视图不会被重新渲染。是正常的吗? –

+0

@ lorraine-bernard:是的,这很正常。你应该手动渲染视图。 –