8

Is it possible to define a catch-all route or an error route in Sammy.js? I know I can bind to 'error' but if no route matches that does not seem to be triggered.

Thanks!

luisgo
  • 2,385
  • 4
  • 24
  • 30

2 Answers2

24

You should override the notFound function.

Like this:

var app = $.sammy('#app', function() {
  this.notFound = function(){
    // do something
  }
});

This is recommended by the author of Sammy.

Aleksey Razbakov
  • 624
  • 8
  • 29
jpbochi
  • 4,366
  • 3
  • 34
  • 43
  • This is appropriate for implementing a 404 Not Found event, but as a catch-all route it's not so practical because `this` will be the `Application`, and not an `EventContext`. So there won't be properties like `path` and `params`. – Fernando Correia Jun 26 '14 at 21:03
9

According to the documentation for Sammy routes,

Paths can be defined as strings or regular expressions.

As such, it should be possible to create a route like this, at the end of your routes, that is a catch-all:

get(/.*/, function() { 
  ...
});
Greg
  • 33,450
  • 15
  • 93
  • 100
  • 1
    minor point - take note of the lack of quotes, this is a literal regular expression. '/.*/' is quite different than /.*/ – Tom Carchrae Nov 06 '12 at 23:26
  • One problem with this approach is that your route will catch even the links that would navigate away from your page. You probably don't want that. – jpbochi Nov 16 '12 at 00:19
  • In my testing with a single page application, this worked and did not trigger when navigating to another page. – Fernando Correia Jun 26 '14 at 21:01