2

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 divs. 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 divs. 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?

makeMonday
  • 2,303
  • 4
  • 25
  • 43

1 Answers1

2

You problem is probably related to not closing and unbinding your views. It is called zombie views. By calling this.remove() and this.off() should cleanup all references to the view.

Have a look at the following:

and

Community
  • 1
  • 1
Timo
  • 349
  • 4
  • 8
  • It was a bit hard for me to solve this, because my Backbone app was not using Backbone "workflow" correctly. But this showed me the way! – makeMonday Apr 17 '15 at 10:09