【问题标题】:How to get a filtered collection如何获得过滤后的集合
【发布时间】:2012-09-21 01:19:38
【问题描述】:

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

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

我的问题是:
如何获得属于BigCollection instance 子集的集合?

这是我的代码。请参阅 cmets 了解更多信息:

// 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
    }
});

【问题讨论】:

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


    【解决方案1】:

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

    // 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;
    

    【讨论】:

      【解决方案2】:

      使用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 是的,你的想法很有效。当我从 firstView 创建新模型时,只有一个问题,视图不会重新渲染。正常吗?
      • @lorraine-bernard :是的,这很正常。您应该手动渲染视图。
      猜你喜欢
      • 1970-01-01
      • 2011-07-23
      • 1970-01-01
      • 2014-03-05
      • 2020-02-02
      • 2021-01-15
      • 1970-01-01
      • 2018-04-16
      • 1970-01-01
      相关资源
      最近更新 更多