Reputation: 71
I'm creating a single page app. I want to remove a view when switching to another view. In the current view, I have a collection of photos. How can I remove the view and the views of photo collection efficiently without memory leaks?
I did the following:
destroy method:
destroy: function(){
this.undelegateEvents();
this.stopListening();
this.$el.empty();
collection.reset();
}
event:
this.listenTo(collection, 'reset', this.resetBoard);
event handling:
resetBoard: function(collection, options){
var models = options.previousModels;
_.each(models, function(model){
model.id = null;
model.destroy();
});
}
here I empty the $el first ($el wiil be used by other views), so that DOM operation can be done at one time. Next, I reset the collection and destroy those models and related views.
Is this logic correct? Is there any better solutions?
Upvotes: 1
Views: 103
Reputation: 36
This is a good article on preventing memory leaks in Backbone Views:
I don't think you need to explicitly remove the models and collections from memory. You just need to make sure that the view is no longer listening for changes in them. This a great overview of garbage collection in javascript and backbone specifically:
What does backbone.js do with models that are not used anymore
In any case, the use of model.destroy() seems a little weird/hacky to me because I think of it as a server operation (deleting the model from the server) and I also wonder if resetBoard will ever execute since you have already called stopListening() when the collection is reset.
Upvotes: 1