简体   繁体   中英

Cannot unbind and close events in my Backbone router

I want to clean up my views in Backbone, before loading new views.

For that, I have searched and added a prototype property to the Backbone object called close :

Backbone.View.prototype.close = function () {

                this.$el.empty();

                //this.$el.unbind();

                this.undelegateEvents();

                console.log('close');
            };

PS the empty() does not seem to work, neither does unbind -- undelegateEvents works.

Now, I cannot seem to figure out hot to call the close function on my router:

define([
        'jquery', 
        'underscore', 
        'backbone',
        'views/userList',
        'views/addUser'
    ], function ($, _, Backbone, UserList, AddUser) {

        var Router = Backbone.Router.extend({

            routes: {
                '' : 'home',
                'new' : 'addUser'
            }
        });

        var initialize = function () {

            var router = new Router();

            router.on('route:home', function () {

                userList = new UserList();

                userList.render();

            });

            router.on('route:addUser', function () {

                addUser = new AddUser();

                addUser.render();

            });

            Backbone.history.start();

        }

        return { 

            initialize : initialize 
        }
    });

Any ideas?

First of all, don't use close , just override the standard remove method:

var SomeBaseView = Backbone.View.extend({
    remove: function () {
        this.$el.empty(); // Instead of this.$el.remove();
        this.stopListening();
        this.undelegateEvents();
        return this;
    }
});

and then derive all your views from SomeBaseView . Messing around with Backbone.View.prototype should be avoided.

Then, stop using global variables like this:

userList = new UserList();

in your route handlers.

Then, start keeping track of which view is currently open so that you can call remove on it before throwing up the next view. A router more like this perhaps:

var Router = Backbone.Router.extend({
    routes: {
        '' : 'home',
        'new' : 'addUser'
    },
    home: function() {
        if(this.currentView)
            this.currentView.remove();
        this.currentView = UserList();
        this.currentView.render();
    },
    addUser: function() {
        if(this.currentView)
            this.currentView.remove();
        this.currentView = AddUser();
        this.currentView.render();
    }
});

You'd drop the router.on calls since you don't need them with this approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM