Reputation: 5036
I've been trying to resolve this for days!
The use-case is one that I would think to be very common; I have a button (<button id="add-item">
) that adds a new item element (<div class="item">
) to a container element (<div id="list">
) which in turn should display a form (<form>
) for the item in a panel (<div id="panel">
). I want to be able to click on the items and have the panel show the form specific to the item.
The problem is that the only item recognizing a click event is the last item added; none of the previously added items views will recognize a click.
I had this working before by having a click event on the List
view on .item
but was told by a prominent member of the Backbone.js community that the item view really should handle a click itself rather than delegating that responsibility up to it's container.
In order to help you who might be able to help to understand the problem I have created an extremely pared down and self-contained example to illustrate. You can see it any of these three (3) places:
Also, if you have any suggestions for how to better structure this code I'm 100% enthusiastic to hear them; I'm new to Backbone.js and do not feel I fully understand it's patterns, practices and idioms.
P.S. I've read everything here on StackOverflow that I can find and I can find nothing that addresses the problem so in case you want to close my question as a duplicate please do me the favor and make sure it actually is a duplicate first.
I'm fixing the code but leaving the errant this.$el.empty()
commented out so others can who have the same issue can learn from this. Thanks to @sardine/@tollmaz for helping me out on this over Twitter.
Upvotes: 0
Views: 99
Reputation: 3223
Per a Twitter conversation, it turns out that the issue is with:
this.$el.empty();
When you create the new item, the events are set up. Upon clicking the item, the select
method is executed. As part of this method, an instance of app.ListView
executes its render
method. Within this method, $el
, which is actually #list
, is emptied. As such, the previously created view with working events is nuked. While it is repopulated visually, the event is never recreated (not sure why this is though).
Upvotes: 1