Anthony Hastings
Anthony Hastings

Reputation: 252

Backbone: View Deletion / Removal

I've a question regarding View Deletion / Removal. I'm aware that you can call the remove method on a view object which will remove the DOM element, and any event listeners that have been bound via listenTo. My question is if you need to do more than that. I normally bind some extra variables within these views and I'm wanting to know if I need to nullify those as well.

An example view:

var myView = Backbone.View.extend({
    el: '#exampleContainer',
    events: {
        'click': 'onClick'
    },
    initialize: function() {
        this.exampleString = 'Hello World';
        this.$exampleSelector = this.$('#exampleChild');
    },
    onClick: function(event) {
        console.log('Hello World');
    }
});

Also, would I be right in assuming that it's not enough to call remove, but I'd also need to nullify the variable pointing at the view?

myView.remove();
myView = null;

Upvotes: 0

Views: 96

Answers (1)

Sascha Gehlich
Sascha Gehlich

Reputation: 1007

AFAIK you should set the variable to null, since JavaScript's garbage collector will only throw away objects that are no longer referenced (or objects that have no route to the root object to be exact). Calling .remove() on the object will not destroy the reference, so it will probably stay in memory.

This post on HTML5Rocks explains what the "Object Graph" is and how JavaScript's garbage collection works. (I think the GC workflow differs from engine to engine, but that's basically how it works)

Upvotes: 1

Related Questions