我有 2 个模型,通过backbone.relational 和backbone.localstorage 实现,它们运行良好。
我有 2 个视图,第一个是“单项”查看器,第二个是具有渲染功能的项视图,可以按照我想要的方式查看我的单项视图,问题是事件不起作用,无论是在父视图中还是在单个项目视图中。我以类似的方式重新实现了该代码,以向您展示它是如何不工作的(代码在 coffeescript 中):
log = console.log
class $.Girl extends Backbone.RelationalModel
localStorage: new Backbone.LocalStorage 'gals'
initialize: -> if typeof @get('id') is 'undefined' then @save() else @fetch()
class $.Girls extends Backbone.RelationalModel
localStorage: new Backbone.LocalStorage 'gals'
relations:[{
type: Backbone.HasMany
key: 'gals'
relatedModel: $.Girl
includeInJson: 'id'
}]
initialize: ->
if typeof @get('id') is 'undefined' then @save() else @fetch()
@fetchRelated()
class $.GirlView extends Marionette.ItemView
tagName: 'tr'
template: (data)-> '<td>'+data.name+' -- '+data.age+'<button>Love</button></td>'
initialize: ->
@listenTo @model,'change',@render
events:
'click button': 'sayLove'
sayLove : -> log 'I Love YOU!'
class $.GirlsView extends Marionette.ItemView
template: (data)->
'<table>
<thead><tr><th>My Gals</th></tr></thead>
<tbody></tbody>
<tfoot><tr><td>I Love Them!</td></tr></tfoot>
</table>'
initialize: (options)->
@models = @model.get('gals').models
@list = []
self = @
_.each @models,(girl)-> self.list.push new $.GirlView {model:girl}
events:
'click th': 'hello'
render: ->
@$el.html(@template {})
self = @
_.each @list,(girl)->
girl.delegateEvents()
self.$('tbody').append girl.render().$el
hello: -> log 'hello'
gal1 = new $.Girl {name:'gal1',age:'22',id:'gal-1'}
gal2 = new $.Girl {name:'gal2',age:'19',id:'gal-2'}
gals = new $.Girls {title:'maGals',id:'gals-1',gals:['gal-1','gal-2']}
gv = new $.GirlsView {model:gals}
gv.render()
$('body').append gv.$el.html()
这对我来说有点像你好世界。任何想法如何实现嵌套 itemViews 与事件工作或此片段的任何其他想法表示赞赏。