【问题标题】:Backbone Routes Not Being Called未调用骨干路由
【发布时间】:2012-12-10 04:18:48
【问题描述】:

我有一个奇怪的问题,我还没有弄清楚。这很简单,这可能就是我遇到问题的原因:)

首先,这是路由表...

routes: {
    '': 'root', //called
    'report': 'report', // called
    'report/add': 'reportAdd', // not called
    'report/print': 'reportPrint', // not called
    'report/settings': 'reportSettings', // not called
},

您会看到我标记了哪些有效,哪些无效。问题归结为所有子路由(即report/add)不匹配。

主干历史在 main.js 中被正确调用,如下所示:

app.Router = new Router();
Backbone.history.start({ pushState: true });

显然,这是在正确的位置,因为路线正在工作,而不是子路线。我已经尝试了Backbone.historyroot 选项和静音parameter 都没有任何运气。

我想这是配置/设置问题,但我找不到任何答案。我究竟做错了什么?非常感谢任何帮助。

顺便说一句,我正在使用 requirejs 和 Backbone Boilerplate,但我不知道这会有什么不同。

更新:虽然提供的答案在技术上是正确的,但问题出在 Backbone Boilerplate 上。请参阅此blog post 的底部以获取说明。我和那里的第一个评论者有同样的问题。

【问题讨论】:

  • 这应该可以正常工作 (jsfiddle.net/ambiguous/stBVC),你在做什么而小提琴不是?
  • 臭气熏天的pushState 选项是问题所在。现在我得到了散列(#report/add)网址,但它确实有效。如何摆脱哈希 URL 并使用 pushState?
  • 所以<a href="#report/add"> 在您不使用pushState 时有效,但在您使用pushState<a href="/report/add"> 失败?
  • 否,<a href="/report/add"> works but it automatically adds the # to the URL. Reloading the page on /report/add` 失败,但访问 #report/add 有效。我知道这很奇怪。
  • 我认为您必须在使用推送状态 URL 时包含某种服务器端 URL 重写,不是吗?即,您必须确保您的服务器在收到/report/add 之类的请求时知道返回/index.html 或其他任何内容。

标签: backbone.js requirejs backbone-boilerplate


【解决方案1】:

正如 cmets 中所讨论的,问题在于,当使用推送状态样式的 URL 时,服务器无法识别主干路由 URL。

为了说明,假设您的应用程序的根位于server/app/index.html,并且您正在尝试使用 Backbone 路由到 /report/print 的 URL。使用 URL 片段路由,这很好:

http://server/app/index.html#report/print

服务器忽略#之后的部分,返回index.html;然后加载主干路由到report/print

但如果您使用 推送状态路由,则 URL 如下所示:

http://server/app/index.html/report/print

服务器会抛出 404 错误,因为它无法识别该路径上的任何内容,因此甚至永远不会加载 Backbone。


解决办法是:

  1. Backbone.js docs 注释,修改服务器代码,使服务器为每个主干路由呈现正确的内容,或者
  2. (我认为这更容易)在 Web 服务器(IISApache)上进行 URL 重写,这样对于像 index.html/report/print 这样的主干路由的任何请求,它将返回 index.htmlindex.html/report/add等。

例如,在 IIS 中,您可以将以下内容放在应用程序根目录下的 web.config 中:

<rewriteMaps>
    <rewriteMap name="StaticRewrites">
        <add key="index.html/report/print" value="index.html" />
        <add key="index.html/report/add" value="index.html" />
        <!-- etc -->
    </rewriteMap>
</rewriteMaps>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-28
    相关资源
    最近更新 更多