骨干路由器与正则表达式和扩展

时间:2014-05-20 10:35:43

标签: regex backbone.js backbone-routing

谷歌搜索时,我看到很多这样的例子:

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函数。

1 个答案:

答案 0 :(得分:2)

我不相信这种语法会起作用:

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");
   }
})
相关问题