Search code examples
javascriptbackbone.js

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


Solution

  • 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