嵌套的ItemViews,事件无法正常工作

时间:2013-04-04 14:12:59

标签: backbone.js marionette

我有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与事件工作或任何其他想法为此片段。

1 个答案:

答案 0 :(得分:0)

在追加子视图后尝试调用delegateEvents:

self.$('tbody').append girl.render().el
girl.delegateEvents()
// or maybe @delegateEvents()? the context should be the child here

修改

$('body').append gv.$el.html()更改为$('body').append @$el