删除模型后删除多个视图
我的应用程序的结构如下:有一个侧边栏,其中包含许多项目,并由 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
的最佳方法是什么?添加诸如 这样的 ID,然后通过数据索引删除项目?我见过有人使用
jQuery.data
将数据绑定到 DOM 树。但这两种解决方案看起来都有点臭。有没有一种优雅的方法来实现这一点?
My application is structured like this: There is a Sidebar which contains many items and is generated by a SidebarView
. The SidebarView
invokes an ItemView
for every item in the sidebar:
render: ->
view = new ItemView({model: the_item})
$(@el).append(view.render().el)
Then there is a ShowView
which displays the item in the main div. There is also a button, which is used to delete the item.
events:
"click #destroy-button" : "destroy"
destroy: () ->
@model.destroy()
this.remove()
return false
It removes the ShowView
from the DOM tree and sends a DELETE request to the server. But what is the best way to remove the ItemView
from the sidebar? Adding IDs like <div class="item" data-index="123"></div>
and then remove the items via the data-index? I have seen somebody using jQuery.data
to bind data to the DOM tree. But both solutions look a bit smelly. Is there an elegant way to accomplish this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的 ItemView 应该处理“删除”按钮。顺序如下:
'destroy'
事件。'destroy'
事件并在事件发生时删除自身。因此,您的 ItemView 将如下所示:
这样,如果您的 Item 模型之一被其他人破坏,您的视图将做出适当的响应。
演示: http://jsfiddle.net/ambigously/KMT74/1/
如果其他人呈现删除按钮,那么您只需要在适当的模型实例上调用
destroy
,ItemView 就会自行删除。有关示例,请参阅演示中的先杀死按钮。您可以在 ItemView 的el
上使用data-id
属性将模型与其视图关联起来,然后执行类似以下操作:但 ItemView 渲染自己的内容会更清晰删除按钮。
另外,这
将是一个问题,因为您将有重复的 id 属性,请改用按钮的类:
Your ItemView should handle the "remove" button. The sequence goes like this:
'destroy'
event from the model.'destroy'
event and removes itself when it happens.So, your ItemView would look something like this:
That way your views will respond appropriately if one of your Item models is destroyed by someone else.
Demo: http://jsfiddle.net/ambiguous/KMT74/1/
And if someone else renders the delete button then you'd just need to call
destroy
on the appropriate model instance and the ItemView would remove itself. See the kill first button in the demo for an example. You could use adata-id
attribute on the ItemView'sel
to associate models with their views and then do something like:but it would be cleaner for the ItemView to render its own delete button.
Also, this:
is going to be a problem as you'll have duplicate
id
attributes, use a class for the button instead: