【问题标题】:marionette composite views rendering a collection呈现集合的木偶复合视图
【发布时间】:2014-07-26 18:44:13
【问题描述】:

我有一个名为 IndexView() 的木偶复合视图。它与名为 index.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 的木偶文档中,它将是项目。 CollectionView 或 CompositeView 会是什么?

【问题讨论】:

  • 您可以发布您的 IndexView 代码吗?
  • 就是 Marionette.CompositeView.extend({template: Template});它在一个 require 模块中,所以在这里发布它不会给你很多细节。这个问题只是让我看看是否有办法做到这一点。我实际上并没有打算以这种方式使用复合视图,我只是好奇。

标签: marionette


【解决方案1】:

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

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

编辑: 如果要遍历模板中的集合,请不要使用 CollectionView。像这样将集合传递给 ItemView:

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

ItemView 会将集合作为模型数组传递给模板上下文的items 属性中的模板。所以你的模板是:

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

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

【讨论】:

  • 你是对的,这就是我使用复合视图的方式。我只是好奇我是否可以以其他方式使用它(通过迭代模板中的集合)以及我将如何去做。谢谢。
【解决方案2】:

Marionette.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
});

您可以覆盖它以将任何对象或对象集合传递给复合视图模板。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 2014-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多