Backbone.js 和 pushState [英] Backbone.js and pushState
问题描述
如果我在主干路由器中启用 pushState,我是否需要在所有链接上使用 return false 或者主干是否自动处理?是否有任何示例,包括 html 部分和脚本部分.
If I enable pushState in the backbone router, do I need to use return false on all links or does backbone handle this automatically? Is there any samples out there, both the html part and the script part.
推荐答案
这是 Tim Branyen 在他的 样板:
This is the pattern Tim Branyen uses in his boilerplate:
initializeRouter: function () {
Backbone.history.start({ pushState: true });
$(document).on('click', 'a:not([data-bypass])', function (evt) {
var href = $(this).attr('href');
var protocol = this.protocol + '//';
if (href.slice(protocol.length) !== protocol) {
evt.preventDefault();
app.router.navigate(href, true);
}
});
}
使用它,而不是单独对链接执行 preventDefault,您让路由器默认处理它们,并通过具有 data-bypass
属性来进行例外处理.根据我的经验,它可以很好地作为一种模式.我不知道周围有什么很好的例子,但自己尝试一下应该不会太难.Backbone 的美在于它的简单性 ;)
Using that, rather than individually doing preventDefault on links, you let the router handle them by default and make exceptions by having a data-bypass
attribute. In my experience it works well as a pattern. I don't know of any great examples around, but trying it out yourself should not be too hard. Backbone's beauty lies in its simplicity ;)
这篇关于Backbone.js 和 pushState的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!