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?
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
destroyon 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-idattribute on the ItemView’selto 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
idattributes, use a class for the button instead: