2012-10-13 69 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 
     } 
    } 
});