0

我正在开发一个应用程序,其中有一个主干集合视图,它在循环中呈现子项视图:

# Collection view:

class Newgvbtool.Views.ProductTypesIndex extends Backbone.View

  template: JST['product_types/index']

  tagName: 'section'

  events: ->
    'click .new-item': @newItem

  initialize: (options)->
    @company_id = options.company_id

    Newgvbtool.vent.on 'product_types_index:add:model', @addToCollection
    Newgvbtool.vent.on 'product_types_index:edit:model', @editModel
    @collection.on 'reset', @render
    @collection.on 'add', @appendItem

  render: =>
    $(@el).html @template()
    @collection.each @appendItem

    @

  newItem: (e) =>
    e.preventDefault()
    @showForm null

  showForm: (model) =>
    if @editView? then @editView.remove()

    @editView = new  Newgvbtool.Views.ProductTypeEdit model: model, company_id: @company_id

    $(@editView.render().el).dialog( 
      show: 
        title: 'Product type'
        effect: 'drop'
        direction: "up"
      hide: "fade"
      autoOpen: true
      modal: true
      draggable: false
      minWidth: 400
      height: "auto"
      resizable: false
    )

  appendItem: (model)=>
    view = new Newgvbtool.Views.ProductType model: model
    $('tbody').append(view.render().el) unless $('#product-types tbody').find("tr[data-id=#{model.id}]").length

  addToCollection: (model) =>
    @collection.update model
    model.trigger('highlight')
    $(@editView.el).dialog 'close'

  editModel: (model) =>
    @showForm model

# Item view

class Newgvbtool.Views.ProductType extends Backbone.View

  template: JST['product_types/product_type']
  tagName: 'tr'

  events:
    'click .delete-item': 'deleteItem'
    'click .edit-item': 'editItem'

  initialize: (options)->
    @model.on 'highlight', @highlight
    @model.on 'change', @render

  render: =>
    $(@el).attr('data-id', @model.get('id')).html @template( model: @model)
    @

  highlight: =>
    @$('td').effect 'highlight', 1000

  deleteItem: =>
    if confirm "Are you sure?"
      @model.destroy wait: true
      $(@el).remove()

  editItem: =>
    Newgvbtool.vent.trigger "product_types_index:edit:model", @model

这是我用来渲染每个项目的模板:

%td
  = @model.get 'name'
%td
  = @model.get 'description'
%td.opts
  %a.edit-item{ href: '#' }
    %span.icon-edit
  %a.delete-item{ href: '#' }
    %span.icon-remove-sign

问题是每次单击一个项目时,都会触发编辑和删除项目事件。

我究竟做错了什么?

提前致谢!

4

1 回答 1

1

错误是我将项目视图添加到集合视图的方式。

我是这样做的:

$('tbody').append(view.render().el)

并且没有正确的事件委托参考,所以我只是添加了@(或这个),现在它就像一个魅力

@$('tbody').append(view.render().el)
于 2013-02-25T13:54:05.910 回答