2014-05-20 36 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"); 
    } 
})