How to delete old backbone views

I have searched the internet for ways to trigger the destruction of old views. There are functions to do this, however, I don't know how to trigger them. Ideally, there would be a way to trigger the destruction on the event of closing a view. I can't find a way how to trigger that particular event.

Upvotes: 0

Views: 126

Answers (2)

David Garvie
David Garvie

Reputation: 1

This old but fantastic piece by Derick Bailey does a great job at explaining the issue and how to solve it. As Monica rightly suggested this relies on view.remove() but you can update your router to destroy your existing view - Try something similar to

if (currentView) { 
  currentView.remove();
  currentView = newView();
}

Upvotes: 0

Monica Olejniczak
Monica Olejniczak

Reputation: 1156

You should call view.remove() to trigger its destruction as specified in the documentation http://backbonejs.org/#View-remove

For example, if you had:

var myView = Backbone.View.extend({
    initialize: function() {
        ...
    },

    render: function() {
        ...
    }
});

You can later call myView.remove() provided you have a reference to myView available.

This method should also remove any event listeners tied to the view if you are using the listenTo (recommended) method as opposed to the on listener. You could also add view.off() to ensure that the events are removed.

Additionally, you will need to add a way for views to listen to a close event so you can call the remove and off methods. You should refer to 1 and 2.

Upvotes: 2

Related Questions