删除模型后删除多个视图

时间:2012-02-06 23:35:22

标签: backbone.js coffeescript

我的应用程序结构如下:有一个侧边栏,其中包含许多项目,由SidebarView生成。 SidebarView为侧边栏中的每个项目调用ItemView

render: ->
  view = new ItemView({model: the_item})
  $(@el).append(view.render().el)

然后有一个ShowView显示主div中的项目。还有一个按钮,用于删除项目。

events:
  "click #destroy-button" : "destroy"

destroy: () ->
  @model.destroy()
  this.remove()

  return false

它从DOM树中删除ShowView并向服务器发送DELETE请求。但是从侧边栏中删除ItemView的最佳方法是什么?添加<div class="item" data-index="123"></div>等ID,然后通过数据索引删除项目?我见过有人使用jQuery.data将数据绑定到DOM树。但这两种解决方案看起来都有点臭。有没有一种优雅的方法来实现这一目标?

1 个答案:

答案 0 :(得分:5)

您的ItemView应该处理“删除”按钮。顺序如下:

  1. 您点击删除按钮。
  2. 在相应的ItemView上触发事件。
  3. ItemView会破坏模型。
  4. 销毁模型会触发模型中的'destroy'事件。
  5. ItemView侦听'destroy'事件,并在事件发生时自行删除。
  6. 所以,你的ItemView看起来像这样:

    class ItemView extends Backbone.View
        events:
            'click .del': -> @model.destroy()
        initialize: ->
            @model.on('destroy', @remove)
        render: ->
            # ...
            @
        remove: =>
            $(@el).remove()
            # And whatever other cleanup tasks you have...
    

    这样,如果您的某个商品模型被其他人销毁,您的观点就会做出相应的反应。

    演示:http://jsfiddle.net/ambiguous/KMT74/1/

    如果其他人渲染删除按钮,那么您只需要在相应的模型实例上调用destroy,然后ItemView将自行删除。有关示例,请参阅演示中的 kill first 按钮。您可以在ItemView的data-id上使用el属性将模型与其视图相关联,然后执行以下操作:

    your_destroy_button_handler: (ev) ->
        item = @collection.get($(ev.target).data('id'))
        item.destroy()
    

    但是ItemView渲染自己的删除按钮会更干净。

    另外,这个:

    events:
      "click #destroy-button" : "destroy"
    

    将会出现问题,因为您将拥有重复的id属性,而是使用按钮的类:

    events:
      "click .destroy-button" : "destroy"