Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
661 views
in Technique[技术] by (71.8m points)

jquery - 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();
    }

});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
    }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...