There are several problems with your code:
Here's the code I come up with. If it doesn't work, post your code somewhere so I can run it myself.
var ViewToDelete = Backbone.View.extend({
template: "ViewToDelete",
tagName: "li",
events: {
"click .delete-button": "deleteItem"
},
initialize: function () {
this.listenTo(this.model, 'remove', this.remove);
},
deleteItem: function() {
this.model.remove();
}
});
The default implementation of view.remove()
will remove this.$el
and stop listening to the model:
remove: function() {
this.$el.remove();
this.stopListening();
return this;
},
EDIT: Thank you for posting your code online. Here's what I think is happening (I'm also documenting for future viewers).
If you take a snapshot, filter on Detached DOM Tree, you see:
The important part is the retaining tree: references that prevent the LI from being deleted. The only significant thing is sizzle-1364380997635
. It doesn't come from your code, it actually comes from jQuery, more specifically from its Sizzle engine. The key comes from here:
https://github.com/jquery/sizzle/blob/master/sizzle.js#L33
If you look further in the code, you see that there's a cache:
https://github.com/jquery/sizzle/blob/master/sizzle.js#L1802
So, in a nutshell, you code does not leak, but jQuery has an internal cache that prevents it from being removed anyway. This cache can only contain a few dozen elements, so it won't retain elements forever.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…