【问题标题】:Backbone router with regex and extend带有正则表达式和扩展的骨干路由器
【发布时间】:2014-05-20 10:35:43
【问题描述】:

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

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

【问题讨论】:

标签: regex backbone.js backbone-routing


【解决方案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");
   }
})

【讨论】:

    猜你喜欢
    • 2014-11-04
    • 2012-04-30
    • 1970-01-01
    • 1970-01-01
    • 2012-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多