Marionette.js CollectionView,只渲染特定的模型

dth*_*ree 6 javascript model-view-controller jquery backbone.js marionette

我正在重构我的Backbone.js应用程序以使用Marionette.js,而我正试图将我的脑袋包裹起来CollectionView.

假设我有几个ItemView模型Cow:

// Declare my models.
var Cow = Backbone.Model.extend({});
var Cows = Backbone.Collection.extend({
  model: Cow
});

// Make my views
var GrassPatch = Marionette.ItemView.extend({
  tagName:  'div',
  template: "<section class='grass'>{{name}}</section>",
})

var Pasture = Marionette.CollectionView.extend({});

// Instantiate the CollectionView,
var blissLand = new Pasture({
  itemView: GrassPatch;
});

// Now, add models to the collection.
Cows.add({
  name: 'Bessie',
  hasSpots: true
});

Cows.add({
  name: 'Frank',
  hasSpots: false
});
Run Code Online (Sandbox Code Playgroud)

现在这就是诀窍.我只想要在我的牧场上有斑点的奶牛.在定义我的CollectionView(牧场)时,我是如何告诉它只关注那些hasSpots===的模型true

理想情况下,我希望在所有事件中都有CollectionView过滤器,但最低限度的是,我如何仅根据其模型属性呈现一些ItemView?

UPDATE

我使用了David Sulc的例子,这就是一个简单的解决方案.这是一个示例实现:

  this.collection = Backbone.filterCollection(this.collection, function(criterion){
    var len = String(criterion).length;
    var a = criterion.toLowerCase();
    return function(model){
      var b = String(model.get('name')).substr(0, len).toLowerCase();
      if (a === b) {
        return model;
      }
    };
  });

  this.collection.add({ name: 'foo' });
  this.collection.add({ name: 'foosball' });
  this.collection.add({ name: 'foo bar' });
  this.collection.add({ name: 'goats' });
  this.collection.add({ name: 'cows' });

  this.collection.filter('foo');

  // -> returns the first three models
Run Code Online (Sandbox Code Playgroud)

Dav*_*ulc 0

正如其他人所建议的,实现此目的的最佳方法是过滤集合以仅包含您想要显示的模型,并将过滤后的集合传递给 CollectionView 进行渲染。

您可以在此处查看一个工作示例:http ://davidsulc.github.io/marionette-gentle-introduction/#contacts使用右上角的输入字段过滤联系人,以仅显示包含该文本(例如“li”)的模型。

这是通过使用处理过滤的特殊集合类型来实现的:https://github.com/davidsulc/marionette-gentle-introduction/blob/master/assets/js/entities/common.js

它在这里实例化: https: //github.com/davidsulc/marionette-gentle-introduction/blob/master/assets/js/apps/contacts/list/list_controller.js#L13

这段代码来自我关于 Marionette 的书