2015-05-05 172 views
0

我有一些主干和路由问题。骨干路由和#

下面的代码:

//routing 
    var AppRouter = Backbone.Router.extend({ 
     routes: { 
      "":"home", 
      "example": "example", 
      "example/:data": "example_data" 
     }, 
     home: function(){ 
      alert('home'); 
     }, 
     example: function(){ 
      alert('example'); 
     }, 
     example_data: function(data){ 
      alert('example '+data); 
     } 
    }); 

    var app_router = new AppRouter(); 
    //Backbone.history.start({pushState: true}); 
    Backbone.history.start(); 

现在,如果我去根网址:

file:///Users/my_user/workspace/project/index.html 

我可以看到警报 '家'。 如果我的网址更改为

file:///Users/my_user/workspace/project/index.html#example 

我可以看到警报“示例”,如果我的网址更改为:

file:///Users/my_user/workspace/project/index.html#example/something 

我可以看到警报“例如什么”。

现在我有两个问题:第一个是我真的很感谢删除'#'符号并使用'/'代替。第二个问题是,如果我分解这一行代码:

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

警报不再工作了。我该如何解决这个问题?

下面是该项目的全码:

<!DOCTYPE HTML> 
<html> 
    <head> 
     <meta charset="UTF-8"> 
     <title>App</title> 
    </head> 
    <body> 
     <div id='test-routing'><a href='#example'>example</a></div> 
     <div id='test-view'></div> 

     <script src="lib/jquery-2.1.3.min.js"></script> 
     <script src="lib/underscore-min.js"></script> 
     <script src="lib/backbone-min.js"></script> 
     <script src="https://sdk.amazonaws.com/js/aws-sdk-2.1.26.min.js"></script> 

     <script> 

     //routing 
     var AppRouter = Backbone.Router.extend({ 
      routes: { 
       "":"home", 
       "example": "example", 
       "example/:data": "example_data" 
      }, 
      home: function(){ 
       alert('home'); 
      }, 
      example: function(){ 
       alert('example'); 
      }, 
      example_data: function(data){ 
       alert('example '+data); 
      } 
     }); 

     var app_router = new AppRouter(); 
     Backbone.history.start({pushState: true}); 
     //Backbone.history.start(); 

     </script> 
    </body> 
</html> 

回答

0

你的第一个问题,我相信你是从主题标签摆脱你的网址,在正确的道路上,你可以使用HTML5 pushState的这一点。

一些帮助是:

http://artsy.github.io/blog/2012/06/25/replacing-hashbang-routes-with-pushstate/

关于你的第二个问题,你的应用好好尝试一下的理由,如果你删除

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

开始是因为骨干路由器没有按没有开始,所以它不会监听hashchange(或pushstate)事件,所以它不会调用你的路由器功能,然后(可能)渲染一个视图。

您需要运行Backbone.history.start以使您的路由器执行任何操作。

您是否评论过其他Backbone.history.start调用?你有没有记录任何错误?

我希望这有助于

编辑:

我想这应该小提琴帮助你: http://jsfiddle.net/sn21jg3x/

祝你好运,告诉我,如果这个工程。

+0

是的,我评论了另一行代码!我不能做一个jsfiddle,但我已经用项目的代码更新了第一个答案! – ste

+0

我想我找到了解决问题的办法,现在我会更新我的答案。 – rikudesu

+0

谢谢,我添加了你给我的代码,'#'的问题解决了,另一方面,如果我用我的项目上的链接/按钮导航,我可以看到链接改变'/'(www .project.com - > www.project.com/resource),但如果我直接粘贴诸如www.project.com/resource之类的东西,则什么也找不到。 – ste