【发布时间】:2012-02-17 12:50:45
【问题描述】:
如果我在骨干路由器中启用 pushState,我需要在所有链路上使用 return false 还是骨干会自动处理?是否有任何示例,包括 html 部分和脚本部分。
【问题讨论】:
如果我在骨干路由器中启用 pushState,我需要在所有链路上使用 return false 还是骨干会自动处理?是否有任何示例,包括 html 部分和脚本部分。
【问题讨论】:
这是 Tim Branyen 在他的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 的美丽在于它的简单性;)
【讨论】:
href 的值标准化为相对路径。
href.slice(protocol.length)实际上是href.slice(0, protocol.length)吗?
$(document.body).on('click', 'a', function(e){
e.preventDefault();
Backbone.history.navigate(e.currentTarget.pathname, {trigger: true});
});
【讨论】:
match() 或 startsWith() (ES 6) 也可用于检查协议。如果您想通过pathname 属性支持绝对网址,请检查location.origin 的基本网址。
function(evt) {
var target = evt.currentTarget;
var href = target.getAttribute('href');
if (!href.match(/^https?:\/\//)) {
Backbone.history.navigate(href, true);
evt.preventDefault();
}
// or
var protocol = target.protocol;
if (!href.startsWith(protocol)) {
// ...
}
// or
// http://stackoverflow.com/a/25495161/531320
if (!window.location.origin) {
window.location.origin = window.location.protocol
+ "//" + window.location.hostname
+ (window.location.port ? ':' + window.location.port: '');
}
var absolute_url = target.href;
var base_url = location.origin;
var pathname = target.pathname;
if (absolute_url.startsWith(base_url)) {
Backbone.history.navigate(pathname, true);
evt.preventDefault();
}
}
【讨论】:
您可以阻止点击 html 中的<a> 标签的默认行为。只需在<script /> 标签内添加以下代码即可。
<script>
$(document).on("click", "a", function(e)
{
e.preventDefault();
var href = $(e.currentTarget).attr('href');
router.navigate(href, true);router
});
</script>
【讨论】: