I have a simple Backbone
app. I am trying to understand the difference created by passing pusState: true
when starting Backbone.History
object.
JavaScript
var r = new (Backbone.Router.extend({
routes: {
"users": "allUsers",
"users/new": "createUser"
},
allUsers: function () {
v.render("showing all users");
},
createUser: function () {
v.render("showing form for creating new user");
}
}));
Backbone.history.start({ pushState: true });
Q1. When I pass pushState: true
and I open localhost:3000/#/users/
, this url automatically redirects to localhost:3000/users
Why does this redirect happen ?
Q2. When I do not pass pushState: true
then redirect does not happen. localhost:3000/#/users/
works fine but localhost:3000/users
does not work ?
What is importance of passing this value in history.start method and why is it important.
Best How To :
Including the pushState
option when starting Backbone.history
tells Backbone to use the HTML5 history API. Basically, this API lets you change the URL in the address bar without reloading the page (see more about it here). Without pushState
, Backbone will use hashes (#
) to change the URL, so it doesn't have to reload the page.
When I pass pushState: true
and I open localhost:3000/#/users/, this url automatically redirects to localhost:3000/users Why does this redirect happen ?
Since you've enabled the history API, Backbone will choose to use actual routes (localhost:3000/users
) instead of hashed routes (localhost:3000/#/users/
). However, it still understands the hashed routes, so it redirects them to the actual route. This way, if you enabled pushState
in an existing application, any user who has a hashed route bookmarked will still be able to use that bookmark. (And of course, any new bookmarks will have the right route).
When I do not pass pushState: true then redirect does not happen. localhost:3000/#/users/ works fine but localhost:3000/users does not work ?
Answer to Q2: When pushState
is not enabled, Backbone will only use hashed routes. So localhost:3000/#/users/
doesn't redirect because it is the "right" route: it will display the content. Depending on how you've set up your server, localhost:3000/users
will either
- Load your app but show no content (or default content)
- Load whatever the
/users
resource is, OR
- Give you a 404 error.