Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to catch all non-matched routes with Backbone?

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?

like image 728
evilcelery Avatar asked Jun 27 '12 23:06

evilcelery


3 Answers

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.

like image 111
evilcelery Avatar answered Nov 18 '22 10:11

evilcelery


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.

like image 28
machineghost Avatar answered Nov 18 '22 09:11

machineghost


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.

like image 2
Pawel Dobierski Avatar answered Nov 18 '22 10:11

Pawel Dobierski