我刚刚开始使用 Backbone.Marionette,在渲染具有多个嵌套项目的结构时遇到问题。我有一本电视指南,其中有很多 channel ,每个 channel 都有很多节目。 json结构为:
[
{
"name":"HBO",
"number":"541",
"programs":[
{
"name":"Game of Thrones"
},
{
"name":"Gojir returns"
}
]
},
{
"name":"Showtime",
"number":"666",
"programs":[
{
"name":"Alex Cook Saves Space"
},
{
"name":"A Clockwork Orange"
}
]
}
]
模型设置如下(使用coffeescript):
class App.Program extends Backbone.Model
class App.Channel extends Backbone.Model
initialize: ->
@programs = new App.Programs(@attributes.programs)
和集合:
class App.Programs extends Backbone.Collection
model: App.Program
class App.Channels extends Backbone.Collection
model: App.Channel
class App.Guide extends Backbone.Collection
model: App.Channel
url: -> 'http://localhost:3000/guide'
initialize: ->
@on('reset', @setChannels)
setChannels: ->
@channels = new App.Channels(@models)
使用 Backbone.Marionette View 渲染以下结构的惯用方法是什么(我省略了我的 View 实现,因为它很糟糕):
<table id="guide">
<thead>
<tr>
<th>Channel</th>
<th>Program 1</th>
<th>Progarm 2</th>
</tr>
</thead>
<tbody>
<tr class="guide-row">
<td class="channel">541:HBO</td>
<td class="program">Game of Thrones</td>
<td class="program">Gojira Returns</td>
</tr>
<tr class="guide-row">
<td class="channel">666:Showtime</td>
<td class="program">Alex Cook Saves Space</td>
<td class="program">A Clockwork Orange</td>
</tr>
</tbody>
</table>
当渲染到 DOM 时, channel 将具有与程序不同的事件处理程序,因此我需要明确地渲染它们。
任何帮助将不胜感激!
最佳答案
好的,我们想出了一个解决方案。这是代码:
%script{type: 'text/html', id: 'channel-template'}
%td.channel <%= number %>: <%= name %>
%script{type: 'text/html', id: 'program-template'}
<%= name %>
class App.Program extends Backbone.Model
class App.Programs extends Backbone.Collection
model: App.Program
class App.ProgramView extends Backbone.Marionette.ItemView
className: 'program'
template: "#program-template"
tagName: 'td'
class App.Channel extends Backbone.Model
initialize: ->
programs = @get("programs")
if programs
@programs = new App.Programs(programs)
class App.Channels extends Backbone.Collection
model: App.Channel
url: -> "http://localhost:3000/guide"
class App.ChannelView extends Backbone.Marionette.CompositeView
className: 'guide-row'
itemView: App.ProgramView
tagName: 'tr'
template: "#channel-template"
initialize: ->
@collection = @model.programs
class App.GuideView extends Backbone.Marionette.CollectionView
id: '#guide'
tagName: 'table'
itemView: App.ChannelView
我们遇到的问题之一是模型、集合和 View 的加载顺序。这对于 View 来说非常重要。我们发现,如果未在集合/复合 View 中定义/加载 itemView,则默认情况下会使用父模板来渲染 itemView。
关于javascript - Backbone.Marionette 和渲染嵌套结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12500507/