0

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
    are you returning false in your event handler, so the default action is cancelled? – Daniel J.G. Nov 19 '14 at 20:36
  • @DanielJ.G. I am not. I just tried it with that and it works. Is this the best practice for accomplishing this with backbone? I'm quite new to backbone. Also, If you want to create an answer I will mark it as correct if you believe this is the best way of doing this. Thanks so much for responding quickly! –  Nov 19 '14 at 20:41

1 Answers1

1

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;
    }
});
Community
  • 1
  • 1
Daniel J.G.
  • 34,266
  • 9
  • 112
  • 112