简体   繁体   中英

backbone.js common event triggered for every view

I'm new to backbone and have been tasked with extending and maintaining a backbone application.

I'm having an issue with a 'log out' button firing for every view loaded. I have created a base class for common view events:

BaseView = Backbone.View.extend({
    logout: function() {
        console.log('logout');
    },
    events: {
        'click .logout':'logout'
    }
})

I then inherit this in the relevant views

DashboardView = BaseView.extend({
    el : '#app',
    render: function(){
        this.$el.html( _.template($('#Dashboard').html()) );
        return this;
    }
})

The templates that are used have the button in <div class="logout"></div>

There are four views making up the section of the site I'm working on and if all four views have been loaded, the logout fires 4 times when clicked.

I've tried several things to solve this, such as unbinding the view when they change and setElement without success.

Firstly, is this an issue I should solve? If so, how do I go about it?

Cheers

Backbone uses jquery's on to register DOM events.
When you instantiate 4 views, 4 event listeners will be bound to the same element if they all have the same parent element defined.

Personally, I tend to create a redirection, using window.location.href , if I'm currently in a page that requires authentication. If I'm in a page that does not require authentication, I just re-render the header, replacing the username with the login (/register) button.

I think I've found a solution.

in the event functions I'm now calling this.undelegateEvents(); eg:

showview : function() {
    this.undelegateEvents();
    app.appRouter.navigate("/dashboard", true);
}

and in the app.js in the appRouter function I call this.DashboardView.delegateEvents(); so:

app.appRouter.on('route:dashboard', function(){
    app.dashboard = new DashboardView();
    app.dashboard.render();
    app.dashboard.delegateEvents();
)}

I would be interest to know if there are any issues with this solution.

Regards

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