Backbone.js and pushState
Backbone.js and pushState
如果我在骨干路由器中启用pushState,我需要在所有链路上使用return false,还是骨干会自动处理?有没有样本,包括html部分和脚本部分。
这是Tim Branyen在他的样板中使用的模式:
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的美丽在于它的简洁;)
$(document.body).on('click', 'a', function(e){
e.preventDefault();
Backbone.history.navigate(e.currentTarget.pathname, {trigger: true});
});
match()
或startsWith()
(ES 6)也可用于检查协议。如果您想通过pathname
属性支持绝对URL,请通过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();
}
}
您可以防止在html中点击<a>
标记的默认行为。只需在<script />
标签中添加以下代码即可。
<script>
$(document).on("click", "a", function(e)
{
e.preventDefault();
var href = $(e.currentTarget).attr('href');
router.navigate(href, true);router
});
</script>
相关文章:
- Selenium WebDriver and JavaScript change
- PHP and Javascript functions
- Javascript Return and if/else
- SetTimeout and clearTimeout in Javascript
- lightbox in html 5 and javascript
- TimelineJS and AngularJS
- timeago.js with datatable and PHP
- javascript button ajax and php
- Ajax and Json with Rails
- Combine onload, onresize and onclick
- php布尔值's小写AND大写和数字布尔值'可以接受
- setTimeout and V8
- pushState()正在驳回'记住密码'对话
- 在页面上记录数据并实现pushstate()的最佳方式
- Jquery post and onclick
- Moment js and IOS
- Android Webview and history.pushState?
- Backbone.js and pushState
- angularjs $location and window.history.pushState
- pushState and SEO