我已经挂了window.onbeforeunload事件和Marionette.AppRouter.navigate方法来检测页面导航并在导航之前运行一些代码。
这些挂钩会在关闭页面或导航时触发,除非是后退或前进按钮导航(Chrome)。
我可以处理路由事件并检测何时调用后退/前进按钮:
Backbone.history.on('route', function(route, params) {
console.log('routing!');
});
但我希望能够在导航之前做到这一点;延伸execute应该让我这样做,但不会被调用:
_.extend(Backbone.Router.prototype, {
execute: function(callback, args) {
if (callback) callback.apply(this, args);
}
});
答案 0 :(得分:2)
结果是覆盖Backbone.Router,然后添加逻辑以有条件地使用callback.apply执行该行:
_.extend(Backbone.Router.prototype, {
route: function(route, name, callback) {
var that = this;
if (!_.isRegExp(route)) route = this._routeToRegExp(route);
if (!callback) callback = this[name];
Backbone.history.route(route, _.bind(function(fragment) {
var args = that._extractParameters(route, fragment);
if (myCustomLogic) {
callback && callback.apply(that, args);
that.trigger.apply(that, ['route:' + name].concat(args));
that.trigger('route', name, args);
Backbone.history.trigger('route', that, name, args);
}
}, that));
return that;
},
});
出现浏览器前进/后退按钮由Backbone.Router处理,其他导航通过Marionette.AppRouter处理。