[英]how can I have CollectionView of CollectionView in marionette.js?
我有一個用例,我想呈現一個collectionViews(或復合視圖)的集合。 使用marionette.js做到這一點的最佳方法是什么?
我的模型結構如下-
A
|
|-- Collection<B>
|
|--Collection<C>
我想渲染如下-
A1
|
|--B1
| |
| C1
| |
| C2
| |
| C3
|
|--B2
|
C4
|
C5
|
C6
做這個的最好方式是什么? 我不希望這樣
A1
|
|--B1
| |
| |--C1
| |
| |--C2
| |
| |--C3
|
|--B2
|
|--C4
|
|--C5
|
|--C6
因此,您可以通過創建一個集合視圖來實現此目的,該視圖可以為試圖顯示的子對象具有一個集合或僅僅是一個模型而除冰。 因此,對於此示例,我建立了一個具有名稱和可選集合的模型,如果使用了該集合,則它將包含模型的集合,而這些模型又可以具有一個可選集合。
然后定義一個集合視圖,該集合視圖將檢查子級是否有一個集合,如果有則將其用作子級。
//collection view that can choose to display another collection view or a model
myApp.Views.View1 = Marionette.CollectionView.extend({
tagName: "ul",
//overridden getChildView to return either another collection view or an item view
getChildView: function (child) {
if (child.get("collection")) {
return myApp.Views.View1;
}
return myApp.Views.ItemView;
},
//set either the collection or the model depending which view we are using
childViewOptions: function (model, index) {
if (model.get("collection")) {
return {
collection: model.get("collection"),
}
} else {
return {
model: model
}
}
}
});
如果沒有,它將僅使用項目視圖來顯示模型
//item view to display final model
myApp.Views.ItemView = Marionette.ItemView.extend({
tagName: "li",
template: _.template('<%= name %>'),
})
它在這里運行-http://jsfiddle.net/leighking2/r5ogoL5h/
如果您想在集合上方顯示正在渲染的模型的名稱,則可以使用復合視圖,這還使我們可以更多地控制鈎入視圖以顯示集合
//collection view that can choose to display another collection view or a model
myApp.Views.View1 = Marionette.CompositeView.extend({
tagName: "ul",
template: _.template('<li><%= name %></li><li><ul class="collectionHook"></ul></li>'),
childViewContainer: ".collectionHook",
//overridden getChildView to return either another collection view or an item view
getChildView: function (child) {
if (child.get("collection")) {
return myApp.Views.View1;
}
return myApp.Views.ItemView;
},
//set either the collection or the model depending which view we are using
childViewOptions: function (model, index) {
if (model.get("collection")) {
return {
model: model,
collection: model.get("collection"),
}
} else {
return {
model: model
}
}
}
});
http://jsfiddle.net/leighking2/kx9kuup0/
唯一的問題是html並不是100%有效的,因為當您在復合視圖中顯示復合視圖時會得到一個雙<ul>
,但是可以進行一些調整,盡管它仍然可以正確呈現。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.