【问题标题】:Optional route parameters in Backbone.js? (again)Backbone.js 中的可选路由参数? (再次)
【发布时间】:2013-01-02 02:56:26
【问题描述】:

我正在尝试在 Backbone 0.9.10 中设置路由。我想匹配以下类型的路线:

/england/
/england/birmingham
/france
/france/paris
... 

等等。这是我目前在路由器中的内容:

var AppRouter = Backbone.Router.extend({
  routes: {
    "": "index",
    "(/:country)": "index",
    "(/:country)(/:city)": "index"
  },
  index: function(country, city) { 
      console.log('index', country, city);
  }
});
var StateApp = new AppRouter();
Backbone.history.start({ pushState: true });

我有两个问题:

  1. 'index' 函数目前根本没有触发,无论我访问的 URL = //england 还是其他任何内容。
  2. 我也不清楚可选参数是否会按照我设置的方式工作 - 可以像这样连续设置两个可选参数吗?我还不知道需要支持多少个国家/地区,所以我确实希望 country 参数成为一个参数,而不是指定单个国家/地区。

如果可能的话,我宁愿使用正确的 URL 路由而不是正则表达式解析。

【问题讨论】:

    标签: javascript backbone.js javascriptmvc backbone-routing


    【解决方案1】:

    如果您想像您的示例一样将所有 url(包括根)路由到一个方法,您只需要定义一个路由:

    routes: {
      "(:country)(/:city)": "index"
    }
    

    因为两个参数都是可选的,所以会匹配:

    • “”(空字符串)
    • “英格兰”
    • “英格兰/伦敦”

    如果您只想要englandengland/london 格式的路由而不想要根页面/,请声明一个单独的空路由,并使:country 部分非可选:

    routes: {
      "" : "home",
      ":country(/:city)": "index"
    }
    

    【讨论】:

    • 天才!太感谢了。我只是不需要最初的斜线。
    【解决方案2】:

    如果您想拥有一个单一的路线,并且可以灵活地更改您希望 URL 的外观。你也可以考虑

    routes: {
     "(/country/:country)(/city/:city)": "index"
    }
    

    匹配

    "" (Empty string)
    "country/england"
    "country/england/city/london"
    

    【讨论】:

      猜你喜欢
      • 2012-03-24
      • 2012-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多