I want to have a 'catch all' route which runs when none of the other defined routes are matched. A type of 404 NotFound error handler.
I've tried adding this, which works but prevents other routes from matching:
this.route(/(.*)/, 'notFound', this.notFound);
Anyone solved this problem before?
Answering here for completeness.
You can do this 2 ways. Define the regular expression using route()
, as in the question. However, due to this bug you would need to define all your routes via the route()
method, and in reverse order (catchall at top). This prevents you from using the routes hash, so (my) preferred method is:
routes: {
'users/search': 'searchUsers',
'users/:id': 'loadUser',
'*notFound': 'notFound'
}
The key '*notFound'
can actually be anything starting with *
. You just require characters after the *
to prevent a parsing error.
There's another, arguably simpler/more elegant way to solve this. Backbone.History.start()
returns either true or false based on whether it matched a route or not. So, if you just do:
if (!Backbone.history.start()) router.navigate('404', {trigger:true});
instead of the usual:
Backbone.History.start();
it will have the same effect as the other answers.
This very tiny plugin gets its job done: https://github.com/STRML/backbone.routeNotFound
It's the most elegant and robust way of solving this issue I've found so far, however please keep in mind that by using it, you are messing with Backbone's internals.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With