我希望能够在“之前”功能中停止路径触发器。上面的功能很棒。它正确地调用“before”方法。调用“before”方法时有没有合适的方法来停止路由?
更新:已解决!
(function () {
_.extend(Backbone.Router.prototype, Backbone.Events, {
route: function (route, name, callback) {
if (!_.isRegExp(route)) route = this._routeToRegExp(route);
if (!callback) callback = this[name];
var router = this;
Backbone.history.route(route, _.bind(function (fragment) {
var args = this._extractParameters(route, fragment);
if (_.isFunction(router.before)) {
if (router.before.apply(this, args) === false) return;
}
callback && callback.apply(this, args);
this.trigger.apply(this, ['route:' + name].concat(args));
if (_.isFunction(router.after)) {
router.after.apply(router, args);
}
Backbone.history.trigger('route', this, name, args);
}, this));
return this;
}
});
}).call(this);
这是路由器代码:
var AppRouter = Backbone.Router.extend({
routes: {
'': 'home',
'help(/)': 'help', // about or /about/
'page(/:id)(/)' : 'page',
'*path' : 'notFound'
},
before: function () {
return false; // the magic
},
after: function () {
},
});
它的工作方式。 return false可以立即停止进程。完善。该解决方案基于knpsck的解决方案。
答案 0 :(得分:3)
before
和after
挂钩 - 是额外的功能。你可以用这种方式实现它(Backbone 1.1.2)
Backbone.Router.prototype.route: function(route, name, callback) {
if (!_.isRegExp(route)) route = this._routeToRegExp(route);
if (_.isFunction(name)) {
callback = name;
name = '';
}
if (!callback) callback = this[name];
var router = this;
Backbone.history.route(route, function(fragment) {
var args = router._extractParameters(route, fragment);
if (_.isFunction(router.before)) {
if (router.before.apply(this, args) === false) return;
}
router.execute(callback, args);
if (_.isFunction(router.after)) {
router.after.apply(router, args);
}
router.trigger.apply(router, ['route:' + name].concat(args));
router.trigger('route', name, args);
Backbone.history.trigger('route', router, name, args);
});
return this;
}