Backbone.js中的可选路由参数?(再次)

Ric*_*ard 5 javascript javascriptmvc backbone.js backbone-routing

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

/england/
/england/birmingham
/france
/france/paris
... 
Run Code Online (Sandbox Code Playgroud)

这就是我目前在路由器中拥有的内容:

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 });
Run Code Online (Sandbox Code Playgroud)

我有两个问题:

  1. "索引"功能目前根本没有触发,无论我转到的网址是什么/,/england或者其他什么.
  2. 我也不清楚可选参数是否会按照我设置的方式工作 - 是否可以在这样的行中有两个可选参数?我不知道我还需要支持多少个国家,所以我确实希望country参数是一个参数,而不是指定各个国家.

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

jev*_*lio 14

如果您希望将所有URL(包括根)路由到一个方法,您只需要定义一个路由:

routes: {
  "(:country)(/:city)": "index"
}
Run Code Online (Sandbox Code Playgroud)

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

  • ""(空字符串)
  • "英国"
  • "英格兰/伦敦"

如果你想只在格式的路线englandengland/london而不是根页面/,宣布独立的空航线,并使:country部分非可选:

routes: {
  "" : "home",
  ":country(/:city)": "index"
}
Run Code Online (Sandbox Code Playgroud)