I have seen many questions about this, but no one is solving my problem.
I have a page with a main div
which has one div
one-image
by default. There is also a button so you can add other div
s. So I have an event click
which appends this other div
template with a "remove" button. Like this:
Image stack
<div class="image-stack">
<div class="one-image">
...
<a id="addImage">Add another image</a>
...
</div>
</div>
Image template
<script type="text/template" id="another-image-template">
<div class="one-image">
...
<a id="addImage">Add another image</a>
<a id="removeImage">Remove image</a>
...
</div>
</script>
View
events: {
'click #addImage' : 'addAnotherImage',
'click #removeImage' : 'removeThisImage'
},
addAnotherImage: function(e) {
var another = $('#another-image-template').html();
$('.images-stack').append(another);
},
removeThisImage: function(e) {
$(e.currentTarget).closest('.one-image').remove();
}
This works fine. When I click the "Add" button, it adds a new one-image
div
under the last one; and when I click the "Remove" button, it removes the div
I clicked. If I change the view and come back to the same view (always created with new
in Backbone), the image-stack
has one div
one-image
only, which is fine. But when I click the "Add" button, it appends two one-image
div
s. And if I repeat the previous steps, it appends three.
I have checked and the function is being called twice (and thrice and so...). I don't understand why this is happening since remove()
is removing the object from the DOM and I always initialize the view
with new
. Any ideas?