Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cleaning views with backbone.js?

I am working on a backbone.js-application and have reached the point where I have a number of routers and views representing each part of my application. In the simplified router example below, I have two locations; account & users.

Both view in each location render their content to a mutual element, named #appcontainer. My common sense says that I should make sure to remove each view before launching another to prevent collisions in bindings, DOM and whatnot.

But as I cannot know for sure whether a view already has been created, I cannot explicitly call previousView.remove() either from inside my router or views.

Would it be sufficient to add $(this.el).empty() to the constructor of each view to clean out any eventual previous bindings and elements from the DOM?

Here's the router example?

var myRouter = Backbone.Router.extend({

    routes: {
        "account": "account",
        "users": "users"
    },

    account: function() {
        view = new AccountView({});
        view.render();
    },

    users: function() {
        view = new UserView({});
        view.render();
    }

});
like image 468
Industrial Avatar asked Jan 31 '12 12:01

Industrial


1 Answers

I have a really simple implementation, I'm just starting my application now and don't know how this is going to hold up in the long run, but it looks something like this:

Edit: Here's what the entire file would look like. this.render will be another function of myRouter.

var myRouter = Backbone.Router.extend({
    routes: {
        'path/to/account' : 'account',
        'path/to/users': 'users'
    }

    account: function() {
        view = new AccountView({});
        this.render(view);
    },

    users: function() {
        view = new UserView({});
        this.render(view);
    },

    render: function (view) {
        //Close the current view
        if (this.currentView) {
            this.currentView.remove();
        }

        //render the new view
        view.render();

        //Set the current view
        this.currentView = view;

        return this;
    }
});
like image 120
MrGrigg Avatar answered Nov 20 '22 03:11

MrGrigg