2012-01-26 110 views
2

使用Backbone路由器時,它會將「頁面」路由視爲#page。使用Backbone.js路由器#!

我可以讓#!作爲默認,而不是#?

我想讓html 4瀏覽器使用#! (http://example.com/#!/page/subpage)和帶有html5歷史記錄的瀏覽器使用普通地址(如http://example.com/page/subpage),而無需使用「!page」作爲路由。

「#!」是使ajax頁面可以被抓取。有關更多信息,請參見http://code.google.com/web/ajaxcrawling/

回答

-2

我dediced使用以下方法:

//Create the Route without routes (just the functions) 
App.Router = Backbone.Router.extend({ 
    "quem-somos": function() { 
     alert("quem-somos"); 
    } 
}); 
//test for html5 history using Modernizr and instantiate the Route with normal urls for true and prefixed routes for false 
if(Modernizr.history){ 
    App.routePrefix=""; 
    App.router = new App.Router({ 
     routes:{ 
      "quem-somos" : "quem-somos" 
     } 
    }); 
}else{ 
    App.routePrefix="!/"; 
    App.router = new App.Router({ 
     routes:{ 
      "!/quem-somos" : "quem-somos" 
     } 
    }); 
} 
Backbone.history.start({pushState: true}); 
//Call navigate when clicking a button 
    App.router.navigate(App.routePrefix+"quem-somos",{trigger: true, replace: true}); 

這樣,我得到http://example.com/quem-somoshttp://example.com/#!/quem-somos每個瀏覽器的支持。

0

看Backbone.js的源之後,它看起來像哈希標籤Backbone.History模塊使用硬編碼。

改變這種最簡單的方法就是修改源本身,上線741(主幹0.5.3):

var hashStrip = /^#*/; 

應改爲:

var hashStrip = /^#!*/; 

您還需要內01改變navigate功能確保「!」出現。上線863:

window.location.hash = this.fragment = frag; 

需要改爲:

window.location.hash = this.fragment = "!" + frag; 

不幸的是,由於它是怎麼寫的Backbone.js的,我不知道還有一個更優雅的方式來解決這個。

+0

感謝您的答案kpeel。現在骨幹承認#!來自地址,但是當使用myRoute.navigate(「page」,true); url片段顯示爲#而不是#! –

+0

啊好抓。不幸的是,這需要對Backbone.js源文件進行另一次編輯。我會更新我的答案。 –

2

你可以只添加!/到您的路線:

routes: { 
    "!/help":     "help", // #!/help 
    "!/page/:subpage":  "search", // #!/search/kiwis 
    "!/page/:subpage/p:page": "search" // #!/search/kiwis/p7 
}, 

然後,您將得到完整的http://example.com/#!/page/subpage網址。

+0

哎呀,我想我只是讀完你的整個問題,並意識到你不想因推狀態而改變路線。對於那個很抱歉!留下這個答案,以防其他人在路上。 – swatkins

+0

它也行得通,但就像kpeel的回答一樣,當使用myRoute.navigate(「page」,true); url片段顯示爲#而不是#! –

+0

嗯,是的,因爲你必須通過完整的路線:'myRoute.navigate(「!/ page」,true);' – swatkins