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.
Without an example of your current routing code I would presume ensuring your catch all route is the last route should work for you
Just add it as the last route in the list. That way it will only be matched as the fallback option.
You can hack it in to backbone like this:
var _loadUrl = Backbone.history.loadUrl;
Backbone.history.loadUrl = function (fragment) {
var result = _loadUrl.apply(Backbone.history, fragment);
// the loadUrl returns false if no route was found.
if(!result){
// call 404 route on router if it exists.
var handler = Backbone.history.handlers.filter( o => o.route.test("404") )
if(handler.length) {
Backbone.history.navigate("/404")
}
}
}
Then in your router you can do like this:
var Router = Backbone.Router.extend({
routes: {
"404": "pageNotFound"
},
pageNotFound: function () {
alert("trigger pageNotFound route")
}
});
I think this should not pass JavaScript to solve, should be the language to solve, for example php. On the server side processing of words, as long as you have the condition you can response head with error number 404