直接链接导航
使用全局事件处理程序来捕获所有点击事件
$(document).on('click', 'a[href^="/"]', function (e) {
var href = $(e.currentTarget).attr('href');
e.preventDefault();
if (doSomeValidation()) {
router.navigate(href, { trigger: true });
}
});
页面刷新/外部网址导航
处理window上的onbeforeunload事件
$(window).on('beforeunload', function (e) {
if (!doSomeValidation()) {
return 'Leaving now will may result in data loss';
}
});
浏览器后退/前进按钮导航
在幕后Backbone.Router 使用Backbone.history 最终利用HTML5 pushstate API。根据您传递给Backbone.history.start 的选项以及您的浏览器的功能,API 将挂钩onhashchange 事件或onpopstate 事件。
深入研究Backbone.history.start 的源代码,很明显无论您是否使用推送状态,都使用相同的事件处理程序,即checkUrl。
if (this._hasPushState) {
addEventListener('popstate', this.checkUrl, false);
} else if (this._wantsHashChange && this._hasHashChange && !this.iframe) {
addEventListener('hashchange', this.checkUrl, false);
} else if (this._wantsHashChange) {
this._checkUrlInterval = setInterval(this.checkUrl, this.interval);
}
因此,我们可以覆盖此方法并在其中执行验证
var originalCheckUrl = Backbone.history.checkUrl;
Backbone.history.checkUrl = function (e) {
if (doSomeValidation()) {
return originalCheckUrl.call(this, e);
} else {
// re-push the current page into the history (at this stage it's been popped)
window.history.pushState({}, document.title, Backbone.history.fragment);
// cancel the original event
return false;
}
};