提问者:小点点

呈现集合的木偶复合视图


我有一个名为IndexView()的木偶复合视图。它绑定到一个称为索引的把手模板。html。

在继续之前,我将注意到,我知道我可以简单地渲染绑定到复合视图的项视图,以输出集合中的每个模型。我将这样做,但我想问我的问题,我的理解。

我从url“/api/users”获取集合

然后得到一份这样的清单

[{"name": "John Doe", "age": 30 }, {"name":"Jane Doe", "age": 31}]

在我的用户控制器里我有代码

var usersCollection = new UsersCollection();
App.contentRegion.show(new IndexView({collection: usersCollection}));
usersCollection.fetch();

如何迭代模板中的集合?

例如。

{{#each ????}}
    <li> {{name}} {{age}} </li>
{{/each}}

哪里会有问号?从木偶留档为ItemView它将是项目。它会是一个集合视图或合成视图?


共2个答案

匿名用户

您不会在模板中迭代集合。CompositeView在集合内部循环,并为集合中的每个模型呈现ItemView。每个ItemView从该集合接收一个模型作为其数据。然后使用传递给模板的模型属性呈现每个单独的ItemView。因此,对于ItemView的模板,不需要在每个项上循环,因为上下文只表示单个项(模型)。因此,您的模板将只是:

<li> {{name}} {{age}} </li>
<li> {{someOtherAttribute}} </li>
<li> {{andYetAnotherAttribute}} </li>

编辑:如果要在模板中的集合上迭代,则不要使用CollectionView。将集合传递给ItemView,如下所示:

view = new ItemView({collection: myCollection});

ItemView将把集合作为模型数组传递到模板上下文的项目属性中的模板。所以你的模板应该是:

{{#each items}}
    <li> {{name}} {{age}} </li>
{{/each}}

由于ItemView现在正在处理所有模型,因此事件将不再针对单个模型,而是针对整个集合。

匿名用户

木偶。CompositeView使用BuildItemView()构建方法将集合的模型添加到其项目视图中。

它还有一个名为serilizeData的函数,其本机实现类似于:

// Serialize the collection for the view.
// You can override the `serializeData` method in your own view
// definition, to provide custom serialization for your view's data.

Marionette.CompositeView = Marionette.CollectionView.extend({
    // composite view implementation
    serializeData: function() {
        var data = {};
        if (this.model) {
            data = this.model.toJSON();
        }
        // your case
        // data.myCollection = this.collection.toJSON();
        // then use myCollection in your template in place of ????
        return data;
    }
    // composite view implementation
});

您可以覆盖该选项,将任何对象或对象集合传递给compositeView模板。

据我所知,没有其他内置方法可以直接从模板访问集合。