A
A
Alexander Zim2015-04-30 06:36:21
JavaScript
Alexander Zim, 2015-04-30 06:36:21

Why does Backbone.js still reload the page when clicking on links?

For example, there is a router with 2 pages. We do it like this:

app.Workspace = Backbone.Router.extend({
  routes: {
    '': function() {
      new app.ShuffleView();
    },
    'shuffle': function() {
      console.log('i\'am shitcoder!');
    }
  }
});
app.router = new app.Workspace();
Backbone.history.start({
  pushState: true
});

I thought that if pushState is enabled, then the backbone itself will start intercepting clicks on links like /shuffle and prevent page reloads, but this does not happen. Nevertheless, the router without pushState works as it should and, for example, if you enter this in the console:
app.router.navigate('/shuffle')
then the route works and the code written in the route is executed.
Considering that the backbone is very minimalistic, I thought maybe they themselves meant this and that I myself should catch clicks on intra-site links and trigger an event with app.route.navigate, but this is fucking insanity, or not?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Prozorov, 2015-04-30
@3um

Already answered on stackoverflow: stackoverflow.com/questions/9328513/backbone-js-an...

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);
    }
  });
}

In general, you correctly understood everything. And this is not insanity at all. This is "the flexibility and lightness of a framework".
Here are some thoughts on why this is so. Backbone can't decide for you which links are considered internal routes and which links should still lead to other pages. Both those and other links will look internal. You must determine the rules for responding to links yourself. Backbone will only decide for you the issue of interacting with the history api.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question