How can I unbind subviews after navigating to a different view in Backbone.js?

46 Views Asked by At

I am new to backbone, and I'm trying to fix a memory leak issue. The project I'm working on has a collection of models that is represented by a list. Each model has a submit button. The button navigates the user to a view for the corresponding model that either lets them assign the model's data to a user in the database, or return to the list view. Everything I described so far works as intended, but when the user returns to the list after navigating from a model view and chooses a different model to submit instead, then the old one will be submitted in addition to the one in the current view.

From what I've read, I know this is caused by the old view listening to events that are still bound to it, and I've looked into the various backbone functions (remove, unbind, listenTo, etc) that can be used to deal with these views. However, I've tried the functions in the view file where I believe the leak is coming from and it still doesn't seem to kill the old views. I'm also using a function in the router that removes views before loading another, but it doesn't seem to remove the subviews for the models that were navigated to in the list.

The initialize function, return function, and events for the view generating leaks

initialize: function (options) {
    if (!(options && options.model)) {
        throw new Error("No item specified for model");
    }
    if (!options.bus) {
        throw new Error("No bus specified");
    }
    if (!options.router) {
        throw new Error("No router specified");
    }

    this.bus = options.bus;
    this.router = options.router;
    this.listenTo(this.model, "returnToList", this.unbind()); //using unbind here after the return button is clicked
},

events: {
    "click #submit": "submit",
    "click #back": "returnToList"
},

//this function will call a function in the router that creates a view for the collection and then calls the loadView function to remove the old view.
returnToList: function () {
    this.router.navigate("exceptionIndex", { trigger: true });
}

This is the function used in the router to remove old views

loadView: function (view) {
    if (this._currentView) {
        this._currentView.remove();
    }

    $("#MainContainer").html(view.render().$el);

    this._currentView = view;
}

The model view should only submit the model that is being referenced for the view, even if the user previously navigated from other model views. The console produces no errors when this issue occurs.

0

There are 0 best solutions below