如何在marionette.js中拥有CollectionView的CollectionView?

时间:2014-11-03 10:02:11

标签: javascript marionette backbone-relational

我有一个用例,我想要渲染一系列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

1 个答案:

答案 0 :(得分:2)

所以你可以通过创建一个集合视图来实现这一点,如果它试图显示的孩子有一个集合或者只是一个模型,那么它可以降级。因此,对于此示例,我已经设置了一个具有名称和可选集合的模型,如果使用该集合,那么它将包含一组模型,而这些模型又可以具有可选集合。

然后定义一个集合视图,集合视图将检查子集是否有集合,如果确实将集合视图用作子集。

//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>但是有一些可以修复的调整,它仍然可以正确呈现

相关问题