在骨干路由中包含root

mar*_*ket 2 javascript ajax router backbone.js

我注意到我正在构建的Backbone应用程序中有一点点怪癖,并且想知道这种行为是否是预期的,或者我是否做错了什么......

我像这样启动Backbone.history:

Backbone.history.start({
  root: '/au/store/',
  pushState: true,
  silent: true
});
Run Code Online (Sandbox Code Playgroud)

要制作后退/前进按钮导航触发路由,我需要它们设置如下:

router = Backbone.Router.extend({
  routes: {
    'au/store/:slug' : 'slug',
    'au/store/?*params' : 'params'
  }
});
Run Code Online (Sandbox Code Playgroud)

这很好用.浏览浏览器历史记录以/au/store/?foo=bar按预期触发"参数"路径.

我遇到的问题是router.navigate()不会触发路线:

router.navigate('?foo=bar', {trigger:true});   // route doesn't trigger
Run Code Online (Sandbox Code Playgroud)

将根添加到URL也不起作用:

router.navigate('au/store/?foo=bar', {trigger:true});  // navigates to /au/store/au/store/?foo=bar
Run Code Online (Sandbox Code Playgroud)

所以我现在使用的解决方法是两次运行所有路由,一次以root为前缀,一次不用:

routes: {
  'au/store/:slug' : 'slug',
  'au/store/?*params' : 'params',
  ':slug' : 'slug',
  '?*params' : 'params'
}
Run Code Online (Sandbox Code Playgroud)

现在它会在后退/前进时触发路由,也可以通过router.navigate()触发.

但这看起来像是一个黑客攻击,肯定会在更复杂的路线上引发问题......

任何人都可以向我解释我做错了什么,或者为什么它没有表现出我对它的期望?

Ahm*_*lfy 7

摆脱路由器中的URL

router = Backbone.Router.extend({
  routes: {
    ':slug' : 'slug',
    '?*params' : 'params'
  }
});
Run Code Online (Sandbox Code Playgroud)

设置silentfalse火的路线

Backbone.history.start({
  root: '/au/store/',
  pushState: true,
  silent: false
});
Run Code Online (Sandbox Code Playgroud)

如果服务器已经呈现整个页面,并且您不希望在启动历史记录时触发初始路由,则传递silent:true.

参考 http://documentcloud.github.com/backbone/#History-start

更新

您还应该使用.htaccess来处理根和重定向.你需要使用这样的东西:

# html5 pushstate (history) support:
<ifModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /au/store/
    RewriteCond %{THE_REQUEST} ^.*/index.php 
    RewriteRule ^(.*)index.php$ /au/store/$1 [R,L] 
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !^/index\.php
    RewriteRule (.*) index.php
</ifModule>
Run Code Online (Sandbox Code Playgroud)

并将其添加到您的头标签中

<base href="/au/store/" />
Run Code Online (Sandbox Code Playgroud)

现在先生,你得到一个完美的工作环境