When using Backbone Router it will treat a "page" route as #page.
Can i make #! as default instead of just # ?
I would like to make html 4 browsers use #! (http://example.com/#!/page/subpage) and browsers with html5 history use normal address like http://example.com/page/subpage without having to use "!page" as the route.
"#!" is to make the ajax page crawlable. See http://code.google.com/web/ajaxcrawling/ for more info.
You can just add the !/
to your routes:
routes: {
"!/help": "help", // #!/help
"!/page/:subpage": "search", // #!/search/kiwis
"!/page/:subpage/p:page": "search" // #!/search/kiwis/p7
},
Then, you will get the full http://example.com/#!/page/subpage
url.
After looking at the Backbone.js source, it looks like the hash tag the Backbone.History
module uses is hard coded in.
The easiest way to change this is to modify the source itself, on line 741 (Backbone 0.5.3):
var hashStrip = /^#*/;
Should be changed to:
var hashStrip = /^#!*/;
You also need to change the navigate
function within Backbone.History
to make sure "!" appears. On line 863:
window.location.hash = this.fragment = frag;
Needs to be changed to:
window.location.hash = this.fragment = "!" + frag;
Unfortunately, due to how it was written in Backbone.js, I'm not sure there is a more elegant way to fix this.
I dediced to use the following approach:
//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});
This way i get http://example.com/quem-somos and http://example.com/#!/quem-somos for each browser support.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.