UPDATE(RELEVANT DETAIL):此复合视图位于复合视图的集合中。
如何使用Backbone.Marionette复合视图构建以下HTML?
<optgroup label="Group 1">
<option>Item 1</option>
<option>Item 2</option>
<option>Item 3</option>
</optgroup>
<optgroup label="Group 2">
<option>Item 4</option>
<option>Item 5</option>
<option>Item 6</option>
</optgroup>
由于我想避免使用<div>
包装器,因此我必须将<optgroup>
指定为tagName。
view = Backbone.Marionette.CompositeView.extend({
collection: some_collection,
itemView: some_itemview,
template: '#some_template', <!-- What goes inside the template? -->
itemViewContainer: 'optgroup',
tagName:'optgroup', <!--specify to avoid the default div-->
<!-- What should I specify in order to pass label="Group1" to the optgroup tag-->
});
答案 0 :(得分:5)
不要使用CompositeView。您不需要包装器模板,因为在这种情况下包装器只是<optgroup>
标签。
使用CollectionView,它不会呈现包装器模板。
对于组#,请使用onRender方法
view = Backbone.Marionette.CollectionView.extend({
collection: some_collection,
itemView: some_itemview,
tagName:'optgroup',
onRender: function(){
this.$el.attr("label", "Group 1");
}
});
答案 1 :(得分:3)
您可以设置视图元素属性,例如initialize或onRender函数,例如:
view = Backbone.Marionette.CompositeView.extend({
...
initialize: function() {
this.$el.attr('label', 'foobar');
}
});
或用以下内容替换initialize:
onRender: function() {
this.$el.attr('label', 'foobar');
}
OR
如果您有现有元素,例如:
<optgroup id="myGroup" label="Group 1">
</optgroup>
您可以这样设置视图元素:
view = Backbone.Marionette.CompositeView.extend({
el: $('#myGroup'),
...
});
答案 2 :(得分:2)
Derick和Lasse的答案相结合,引出了我的解决方案。 onRender
是我所遗漏的。以下是未来读者的摘要。
嵌套集合视图的结构:
Collection of Collections --> Collection --> Item
--> Collection --> Item
--> ... etc.
CollectionOfCollections =
Backbone.Marionette.CollectionView.extend({
collection: myCollectionOfCollections,
itemView: Collection <!--this refers to the next Collection view below-->
});
收藏 =
Backbone.Marionette.CollectionView.extend({
collection: myCollection,
itemView: ItemView, <!-- again... the next view below -->
tagName: 'optgroup',
Nested collections with Backbone.Marionette
<!-- IF YOU ARE PASSING A SIMPLE ARRAY,
IT MUST BE CONVERTED TO A REAL COLLECTION FIRST -->
initialize: function(){
var xyz = this.model.get('abc');
this.collection = new Backbone.Collection.extend({});
});
onRender: function(){
<!-- Here's where you insert the attribute into the tag -->
this.$el.attr('label', this.model.get('name'));
}
});
});
ItemView =
ModalDropdownEntryView = TourView.extend({
model: myModel,
template: '#myTemplate',
tagName: 'option',
});