How do I destroy this Backbone.js View instance?
12,493
Solution 1
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.
Solution 2
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();
}
Related videos on Youtube
Author by
TIMEX
Updated on June 04, 2022Comments
-
TIMEX over 1 year
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.
-
Johnny Oshika almost 12 yearsYou don't need _.bindAll(this, 'toggleCheckFriend'). The context for DOM event callbacks will automatically be the view.
-
rkw almost 12 years@JohnnyO: I mainly have that in there for piping commands. Just in case there are elements that can trigger it besides the user directly triggering it. (i.e. the page has a CheckAllCheckBox)