如果我在backbone路由器中启用了pushState,我是否需要在所有链路上使用return false,或者backbone会自动处理此问题?有没有任何示例,包括html部分和脚本部分。
发布于 2012-02-17 16:16:10
这是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的美在于它的简单性;)
发布于 2014-02-27 23:47:06
$(document.body).on('click', 'a', function(e){
e.preventDefault();
Backbone.history.navigate(e.currentTarget.pathname, {trigger: true});
});
发布于 2015-09-03 12:03:07
match()
或startsWith()
(ES 6)也可用于检查协议。如果要按pathname
属性支持绝对urls,请按location.origin
检查基URL。
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();
}
}
https://stackoverflow.com/questions/9328513
复制