0

更新(相关详细信息):此复合视图位于复合视图的集合中。

如何使用 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-->
});
4

3 回答 3

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");
    }

});
于 2012-12-05T14:03:25.853 回答
3

您可以在例如 initialize 或 onRender 函数中设置视图元素属性,例如:

view = Backbone.Marionette.CompositeView.extend({
    ...

    initialize: function() {
        this.$el.attr('label', 'foobar');
    }
});

或将初始化替换为:

    onRender: function() {
        this.$el.attr('label', 'foobar');
    }

或者

如果您有一个现有元素,例如:

<optgroup id="myGroup" label="Group 1">
</optgroup>

您可以这样设置视图的元素:

view = Backbone.Marionette.CompositeView.extend({
    el: $('#myGroup'),

    ...
});
于 2012-12-05T07:41:23.820 回答
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',

使用 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'));
     }
   });
});

项目视图 =

ModalDropdownEntryView = TourView.extend({
    model: myModel,
    template: '#myTemplate',
    tagName: 'option',
});
于 2012-12-05T17:31:31.227 回答