2014-07-26 75 views
1

我有一个名为IndexView()的木偶合成视图。它绑定到一个名为index.html的句柄模板。木偶合成视图呈现集合

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

我取从URL集合 “/ API /用户”

,并得到这样

[{"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会是什么?

+0

你能发布你的IndexView代码吗? –

+0

这只是Marionette.CompositeView。extend({template:Template});它在一个需要的模块中,因此在这里发布不会给你很多细节。这个问题只是为了看看是否有办法做到这一点。实际上我没有任何用这种方式使用Composite视图的意图,我只是好奇而已。 – decapo

回答

0

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

您可以覆盖此传递任何对象或对象的集合CompositeView中的模板。

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

2

您不会迭代模板中的集合。 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控件正在处理所有车型,您的事件将不再是一个单一的模式,而是整个集合。

+0

你是对的,这是我如何使用复合视图。我只是好奇,如果我可以用另一种方式使用它(通过迭代模板中的集合)以及我将如何去做。谢谢。 – decapo

+0

@decapo,你可以做到这一点。检查我的编辑。 – Simon

相关问题