2012-02-17 36 views
37

如果我在骨幹路由器中啓用pushState,是否需要在所有鏈路上使用return false,或者主幹是否自動處理?是否有任何樣本,包括html部分和腳本部分。Backbone.js和pushState

回答

67

這是他boilerplate格局添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屬性作出例外。根據我的經驗,它很適合作爲一種模式。我不知道周圍有什麼好的例子,但是自己嘗試一下不應該太難。骨幹的美在於它的簡單性;)

+0

太棒了,它效果很好。謝謝! – Marcus 2012-02-18 13:53:57

+4

只是一個頭 - 我注意到,在我期待相對URL的某些情況下,IE7返回絕對URL。爲了處理這種情況,您需要在調用導航之前將'href'的值標準化爲相對路徑。 – lupefiasco 2012-04-28 08:06:43

+1

只是好奇,什麼是(href.slice(protocol.length)!==協議)在做什麼? – dezman 2014-01-28 22:45:45

9
$(document.body).on('click', 'a', function(e){ 
    e.preventDefault(); 
    Backbone.history.navigate(e.currentTarget.pathname, {trigger: true}); 
}); 
1

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(); 
    } 
} 
0

您可以防止在html中點擊<a>標籤的默認行爲。只需在<script />標記內添加下面的代碼即可。

<script> 
$(document).on("click", "a", function(e) 
{ 
    e.preventDefault(); 
    var href = $(e.currentTarget).attr('href'); 
    router.navigate(href, true);router 
}); 
</script>