2012-10-13 73 views
2

我有一个运行在knockout.js应用程序中的sammy.js。我目前正在尝试重定向缺少尾部斜杠的路由(例如/#/stop/1/100032)。我想将所有缺少尾部斜杠的页面重定向到带有斜杠的页面。如何从没有尾部斜线的页面重定向到尾部斜线的页面

使事情变得复杂,我还想在没有这样的路线的情况下有一个错误页面。

function RoutesViewModel() { 
    var self = this; 

    self.router = Sammy(function() { 
     this.get('/#/stop/:agency_id/:stop_id/', function() { 
      app.page.state('bus'); 
      app.stop.setCurrentById(this.params['agency_id'], this.params['stop_id']); 
      mixpanel.track('stop page load', { 
       'route': '/#/stop/' + this.params['agency_id'] + '/' + this.params['stop_id'] + '/', 
      }); 
     }); 
     this.get('/(.*[^\/])', function() { 
      this.redirect('/',this.params['splat'],'/'); 
     }); 
    }); 

    self.router.error = function (message, error) { 
     app.page.header("Unable to find your page"); 
     app.page.message("The page you've requested could not be found.<br /><a href=\"/\">Click here</a> to return to the main page."); 
    } 

    self.run = function() { 
     self.router.run(); 
    } 
} 

以上是我到目前为止选择的路线。不幸的是,当我转到上面的示例url时,页面会加载错误,而不是正确的/#/stop/1/100032/

任何帮助将不胜感激。

+0

您是否曾找到解决方案? – Chad

回答

0

我知道这是一个老问题,但我也遇到过这个问题。按照http://sammyjs.org/docs/routes路由是正则表达式。所以这个工作对我来说:

this.get('#/foo/:id/?', function() { 
0

我有同样的问题,并决定用一个包罗万象的在我的萨米的建立最终解决它。我的解决方案删除了​​后面的斜线(如果有的话),但是您可以轻松地做相反的操作,而不是添加斜线:

Sammy(function() { 
    this.get('#', function() { 
     // ... 
    }); 
    this.notFound = function (method, path) { 
     if (path[path.length - 1] === '/') { 
      // remove trailing slash 
      window.location = path.substring(0, path.length - 1); 
     } else { 
      // redirect to not found 
     } 
    } 
});