所以,你可以通过创建可除冰如果试图显示孩子有一个集合,或者只是一个模型集合视图实现这一目标。因此,对于这个例子,我建立了一个模型,它有一个名称和一个可选集合,如果集合被使用,那么它将包含模型集合,而集合又可以有一个可选集合。
然后定义一个集合视图,集合视图将检查孩子是否有一个集合,它是否会将集合视图用作子集。
//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>
,当你显示一个复合视图内,但有一些调整,可能是固定的复合视图,它仍然呈现正确,但。
我有一个相当复杂的结构,每个级别的不同视图,即A,B和C的不同视图。我有很多事件要处理,更重要的是,我想要一个排序功能(点击排序按钮时,DOM应该排序)。我怎样才能做到这一点? – pratiksanglikar 2014-11-03 10:06:04
任何源代码的例子? – 2014-11-03 12:41:58