我正在重构我的 Backbone.js 应用程序以使用 Marionette.js,并且我正在尝试围绕 CollectionView
进行思考。
假设我有几个模型为 Cow
的 ItemView
:
// 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
});
这就是诀窍了。我只想要我牧场上有 Blob 的奶牛。在定义我的 CollectionView(牧场)时,我如何告诉它只关注那些 hasSpots
=== true
的模型?
理想情况下,我希望在所有事件中都使用 CollectionView 过滤器,但至少,我如何根据模型属性只渲染一些 ItemView?
更新
我使用了 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
最佳答案
Marionette 在 v2.4.1 中为您处理此问题。
参见 CollectionView.filter方法。
以下内容来自文档:
var cv = new Marionette.CollectionView({
childView: SomeChildView,
emptyView: SomeEmptyView,
collection: new Backbone.Collection([
{ value: 1 },
{ value: 2 },
{ value: 3 },
{ value: 4 }
]),
// Only show views with even values
filter: function (child, index, collection) {
return child.get('value') % 2 === 0;
}
});
// renders the views with values '2' and '4'
cv.render();
// change the filter
cv.filter = function (child, index, collection) {
return child.get('value') % 2 !== 0;
};
// renders the views with values '1' and '3'
cv.render();
// remove the filter
// note that using `delete cv.filter` will cause the prototype's filter to be used
// which may be undesirable
cv.filter = null;
// renders all views
cv.render();
关于javascript - Marionette.js CollectionView,只渲染特定模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18604233/