Until now, we've focused on what happens when a route matches, but what happens when the user visits a URL that doesn't have a matching route? This can happen, for instance, because of a stale link or because the user mistyped a URL. On a traditional website, the server will handle this by throwing a 404
error, but on a Backbone-powered site, the Router
class will just do nothing, by default. This means that if you want to have a 404
page on your site, you'll have to create it yourself.
One way to do this is to rely on the start
method. This method returns true
or false
depending on whether any matching routes are found for the current URL:
if (!Backbone.history.start()) { // add logic to handle the "404 Page Not Found" case here }
However, since that method will only be called once, when the page is first loaded, it won't allow you to catch nonmatching routes that occur after the page is loaded. To catch these cases, you'll need to define a special 404
route, which you can do using the routing string's splat
syntax:
var SiteRouter = Backbone.Router.extend({ initialize: function(options) { this.route('normalRoute/:id', 'normalRoute'), this.route('*nothingMatched', 'pageNotFoundRoute'), }, pageNotFoundRoute: function(failedRoute) { alert( failedRoute + ' did not match any routes'), } });
13.59.205.183