If you want to implement custom routing in any framework, it can be done by creating a Router extension. This process is usually quicker than seeking help online. While I'm not certain if Backbone supports this feature out of the box, I will investigate the code to confirm.
The key method for achieving custom routes is as follows:
route: function(route, name, callback) {
if (!_.isRegExp(route)) route = this._routeToRegExp(route);
if (!callback) callback = this[name];
Backbone.history.route(route, _.bind(function(fragment) {
var args = this._extractParameters(route, fragment);
callback && callback.apply(this, args);
this.trigger.apply(this, ['route:' + name].concat(args));
Backbone.history.trigger('route', this, name, args);
}, this));
return this;
},
Essentially, this method simply executes the callback function without blocking anything else.
You have the freedom to extend this functionality, for example, like so:
var RouteError(message) {
this.name = "RouteError";
this.message = (message || "");
}
RouteError.prototype = Error.prototype;
var MyRouter = function (){
Backbone.Router.apply(this, arguments);
};
MyRouter.prototype = Object.create(Backbone.Router.prototype);
MyRouter.prototype.constructor = MyRouter;
_.extend(MyRouter.prototype, {
route: function(route, name, callback) {
if (!_.isRegExp(route)) route = this._routeToRegExp(route);
if (!callback) callback = this[name];
Backbone.history.route(route, _.bind(function(fragment) {
var args = this._extractParameters(route, fragment);
try {
callback && callback.apply(this, args);
}
catch(e)
{
if (e instanceof RouteError)
return this;
else
throw e;
}
this.trigger.apply(this, ['route:' + name].concat(args));
Backbone.history.trigger('route', this, name, args);
}, this));
return this;
},
});
Alternatively, you could modify the behavior like this:
var loadUrl = Backbone.History.prototype.loadUrl;
Backbone.History.prototype.loadUrl = function (fragmentOverride){
try {
loadUrl.apply(this, arguments);
}
catch (e){
if (e instanceof RouteError)
return ;
else
throw e;
}
};
(Please note that these examples have not been tested...)
Based on my understanding, it seems that native support for this feature may be lacking in Backbone...