2011-09-05 75 views

回答

63

您需要啓用pushState的

Backbone.history.start({pushState: true})

http://backbonejs.org/#Router

http://backbonejs.org/#History

編輯:正如在評論中指出,這將僅對支持pushState的瀏覽器,沒有瀏覽器工作將回落到哈希方法。沒有真正的解決方法,你可以啓用現代瀏覽器並回退,或者只爲所有瀏覽器使用散列。

+0

下面是一個類似的問題,一些更多的信息[鏈接](http://stackoverflow.com/a/8280389/706466) –

+7

應當指出的是,這僅僅是在對歷史支持的瀏覽器可用API(現代瀏覽器)。沒有歷史API支持的瀏覽器將使用散列。 – Kenzic

10

Backbone Boilerplate有一個很好的助手,可以實現pushstate。有時我想繞過我的路由器使用它。

// Trigger the initial route and enable HTML5 History API support, set the 
// root folder to '/' by default. Change in app.js. 
Backbone.history.start({ pushState: true, root: app.root }); 

// All navigation that is relative should be passed through the navigate 
// method, to be processed by the router. If the link has a `data-bypass` 
// attribute, bypass the delegation completely. 
$(document).on("click", "a[href]:not([data-bypass])", function(evt) { 
    // Get the absolute anchor href. 
    var href = { prop: $(this).prop("href"), attr: $(this).attr("href") }; 
    // Get the absolute root. 
    var root = location.protocol + "//" + location.host + app.root; 

    // Ensure the root is part of the anchor href, meaning it's relative. 
    if (href.prop.slice(0, root.length) === root) { 
    // Stop the default event to ensure the link will not cause a page 
    // refresh. 
    evt.preventDefault(); 

    // `Backbone.history.navigate` is sufficient for all Routers and will 
    // trigger the correct events. The Router's internal `navigate` method 
    // calls this anyways. The fragment is sliced from the root. 
    Backbone.history.navigate(href.attr, true); 
    } 
});