Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I destroy this Backbone.js View instance?

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.

like image 253
TIMEX Avatar asked Dec 04 '11 22:12

TIMEX


2 Answers

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.

like image 55
sdailey Avatar answered Oct 03 '22 01:10

sdailey


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();

    }
like image 41
Esailija Avatar answered Oct 03 '22 00:10

Esailija