Reputation: 271774
var CheckboxView = Backbone.View.extend({
tagName:'div',
template: _.template(item_temp,{}),
events:{
'click .checkoff_friend':'toggleCheckFriend',
},
initialize: function(){
},
render:function(){
},
toggleCheckFriend:function(){
//destroy this View instance.
}
});
var cv = new CheckboxView();
How do I destroy the instance? When toggle is activated, I want the instance of that view to dissapear forever.
Upvotes: 5
Views: 12583
Reputation: 2030
My answer for a similar question was received well, and has worked well for me. Here's a look at my destroy_view function
(orig. question https://stackoverflow.com/a/11534056/986832) Response:
I had to be absolutely sure the view was not just removed from DOM but also completely unbound from events.
destroy_view: function() {
//COMPLETELY UNBIND THE VIEW
this.undelegateEvents();
$(this.el).removeData().unbind();
//Remove view from DOM
this.remove();
Backbone.View.prototype.remove.call(this);
}
Seemed like overkill to me, but other approaches did not completely do the trick.
Upvotes: 6
Reputation: 7297
Does that View have a model behind it?
If you want the model removed (from the db), you can use: this.model.destroy()
After that, you can remove just the View itself from the DOM by calling this.remove()
. Documentation mentions that it is the equivalent of $(this.el).remove()
.
Note that the 'this' above refers to the View itself, so you would have to _.bindAll(this, 'toggleCheckFriend')
Upvotes: 0
Reputation: 140230
Do not assign the instance to any variable (I don't see any need to since Views in backbone are driven by events), and in your toggleCheckFriend
method remove all data and events, which makes the instance available for garbage collection.
toggleCheckFriend:function(){
$(this.el).removeData().unbind();
}
Upvotes: 3