Backbone.js and pushState

This is the pattern Tim Branyen uses in his boilerplate:

initializeRouter: function () {
  Backbone.history.start({ pushState: true });
  $(document).on('click', 'a:not([data-bypass])', function (evt) {

    var href = $(this).attr('href');
    var protocol = this.protocol + '//';

    if (href.slice(protocol.length) !== protocol) {
      evt.preventDefault();
      app.router.navigate(href, true);
    }
  });
}

Using that, rather than individually doing preventDefault on links, you let the router handle them by default and make exceptions by having a data-bypass attribute. In my experience it works well as a pattern. I don’t know of any great examples around, but trying it out yourself should not be too hard. Backbone’s beauty lies in its simplicity 😉

Leave a Comment