如果您编写路由器扩展,那么每个框架都是可能的。这可能比问这个问题花费的时间更少。我不知道它是否在主干中支持,我会检查代码。
这是您正在寻找的方法:
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;
},
如您所见,它只是运行回调,并没有阻止任何内容。
例如,您可以通过以下方式扩展它:
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;
},
});
或者这样:
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;
}
};
(我没有检查任何这些......)
所以我不认为这在 Backbone 中是原生支持的......