Backbone event handling causes unwanted reload, can I avoid this?

107 views Asked by At

I have a page with complex views that I want to be linkable.

Example: When a certain panel is opened, I have the url change to www.example.com/#panel-1.

This is working fine.

I want to use Backbone to act as a normal event handler without changing routes or reloading. I have:

var ApplicationView = Backbone.View.extend({

el: $('body'),

events: {
    'click #comingsoon': 'displayComingSoon'
},

displayComingSoon: function(){
    //some jquery code to add or remove classes
}

});

but my problem is after this code executes, the page reloads and the classes are removed. Do I have to specify a route to use backbone for event handling? I would rather the URL not change for this event.

1

There are 1 answers

1
Daniel J.G. On BEST ANSWER

Returning false is one of the ways in Javascript of cancelling the default action of an event (For more info see this question and this other question). For example a click event on a link would cause the browser to navigate to that link, but if you return false in the event handler this default behaviour is cancelled.

So you can apply this to the event handlers in your backbone view:

var ApplicationView = Backbone.View.extend({
    el: $('body'),
    events: {
        'click #comingsoon': 'displayComingSoon'
    },
    displayComingSoon: function(){
        //some jquery code to add or remove classes
        return false;
    }
});