2014-05-20 34 views
1

google搜索的時候,我看到很多的例子是這樣的:用正則表達式骨幹路由器和擴展

App.Router = Backbone.Router.extend({ 
    routes: { 
     '': 'index', 
     'show/:id': 'show' 
    }, 

    index: function(){ 
     $(document.body).append("Index route has been called.."); 
    }, 
    show: function(id){ 
     $(document.body).append("Show route with id: " id); 
    } 
}); 

這將如何實現像使用正則表達式?

我想是這樣的:

App.Router = Backbone.Router.extend({ 
    routes: { 
     '': 'index', 
     /show/(\d+:id)/: 'show' 
     /show/([A-Za-z]+:other)/: 'showSpecial' 
    }, 

其中第一個正則表達式匹配/show/[any number]並將在id參數的show功能號碼。

以及第二個正則表達式匹配/show/[any word]並將other參數中的單詞傳遞給showSpecial函數。

+0

檢查這一項[骨幹路由的正則表達式(HTTP://計算器。 COM /問題/ 18061925 /骨幹路由正則表達式) –

回答

1

我不相信這句法將工作:

App.Router = Backbone.Router.extend({ 
    routes: { 
     '': 'index', 
     /show/(\d+:id)/: 'show' 
     /show/([A-Za-z]+:other)/: 'showSpecial' 
}, 

相反,你可以寫這樣的:

App.Router = Backbone.Router.extend({ 
    initialize: function() { 
     this.route(/^$/, 'index'); 
     this.route(/^show\/(\d+)$/,"show"); 
     this.route(/^show\/([A-Za-z]+)/, "showSpecial"); 
    } 
})