Search code examples
javascripthtmlbackbone.js

When using push state redirect in Backbone, how can I keep the "back" button working?


In a Backbone render, sometimes I need to redirect a page.

For example, let's say someone lands on the "index" page and then clicks "login". In the login view, I use this code to redirect to register page:

Backbone.history.navigate('/register', true);

However, when the user clicks back, the user is not taken to "index". Instead, it is taken to "login", which redirects him back to 'register'.

How can I make sure the user goes back to index when he pushes back?


Solution

  • You can pass the 'replace' option when you call .navigate.

    Backbone.history.navigate('/register', {replace: true});
    

    This is set out in the documentation: "To update the URL without creating an entry in the browser's history, set the replace option to true."

    (As a side note, I'd be cautious about calling .navigate directly on Backbone.history; the source code suggests it will work fine, but it's undocumented.)