2012-01-26 106 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