Destroy or remove a view in Backbone.js

Ad Taylor picture Ad Taylor · Jul 4, 2011 · Viewed 108.2k times · Source

I'm currently trying to implement a destroy/remove method for views but I can't get a generic solution to work for all my views.

I was hoping there would be an event to attach to the controller, so that when a new request comes through it destroys previous views then loads the new ones.

Is there any way to do this without having to build a remove function for each view?

Answer

sdailey picture sdailey · Jul 18, 2012

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.