tiny_mouse
tiny_mouse

Reputation: 489

Backbone per instance event bindings

I have a view that creates a sub-view per item in the list. Generically let's call them ListView and ListItemView. I have attached an event as follows on ListItemView:

events: {
    "click .remove": "removeItem"
}

I have template-generated html for ListItemView that is approximately like the following (swapped lb/rb for {/} so you can see the "illegal" html):

{div class="entry" data-id="this_list_item_id"}
SOME STUFF HERE
{div class="meta"}
{a class="remove" href="javascript:;"}[x]{/a}
{/div}
{/div}

The problem is, when the click on any of the [x]'s, ALL of the ListItemViews trigger their removeItem function. If I have it go off of this model's id, then I drop all the items on the page. If I have it go off the clicked item's parent's parent element to grab the data-id, I get a delete for EACH ListItemView instance. Is there a way to create an instance-specific event that would only trigger a single removeItem?

If I have ListView hold a single instance of ListItemView and reassign the ListItem model and render for each item in the list it works. I only end up with one action (removeItem) being triggered. The problem is, I have to find the click target's parent's parent to find the data-id attr. Personally, I think the below snippet is rather ugly and want a better way.

var that = $($(el.target).parent()).parent();

Any help anyone gives will be greatly appreciated.

Upvotes: 1

Views: 331

Answers (2)

Typo Johnson
Typo Johnson

Reputation: 6044

A wild guess but possible; check that your rendered html is valid. It might be possible that the dom is getting in a tiz due to malformed html

Upvotes: 0

Paul
Paul

Reputation: 18597

It seems like your events hash is on your ListView.

If it is, then you can move the events hash to ListItemView and your removeItem function can be the following

removeItem: function() {
  this.model.collection.remove(this.model);
}

If this isn't the case, can you provide your ListView and ListItemView code so I can look at it.

Upvotes: 1

Related Questions