簡體   English   中英

將Backbone.js路由器與#一起使用!

[英]Use Backbone.js router with #!

使用Backbone Router時,它將“頁面”路由視為#page。

我可以做#! 作為默認值,而不只是#?

我想讓html 4瀏覽器使用#! (http://example.com/#!/page/subpage)和具有html5歷史記錄的瀏覽器使用正常地址,例如http://example.com/page/subpage,而不必使用“!page”作為路由。

“#!” 是為了使Ajax頁面可抓取。 有關更多信息,請參見http://code.google.com/web/ajaxcrawling/

您可以將!/添加到您的路線中:

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

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

在查看Backbone.js源代碼之后,看起來好像硬編碼了Backbone.History模塊使用的哈希標簽。

更改此設置的最簡單方法是在741行(主干0.5.3)上修改源本身:

var hashStrip = /^#*/;

應更改為:

var hashStrip = /^#!*/;

您還需要更改Backbone.Historynavigate功能,以確保“!” 出現。 在863行上:

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

需要更改為:

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

不幸的是,由於它是用Backbone.js編寫的,因此我不確定有更優雅的方法來解決此問題。

我致力於使用以下方法:

//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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM