【问题标题】:Routes not processed未处理的路线
【发布时间】:2012-03-07 07:36:57
【问题描述】:

我有一个node.js(服务器)和backbone.js(客户端)应用程序-我可以在页面上加载和初始化我的骨干网应用程序......并初始化路由器,但我的默认路由(“。* ") 没有被调用。我可以在初始化路由器后手动调用 index 函数,但是当我在 Rails 上构建主干应用程序时,我不必采取这一步。

有人知道为什么会这样吗?

添加代码(在咖啡脚本中):

class NodeNetBackbone.Routers.RegistryPatients extends Backbone.Router
  routes:
    ''          : 'index'
    '.*'        : 'index'
    '/index'    : 'index'
    '/:id'      : 'show'
    '/new'      : 'new'
    '/:id/edit' : 'edit'

  initialize: ->
    console.log 'init the router'
    @registry_patients = new NodeNetBackbone.Collections.RegistryPatients()
    # TODO: Figure out why this isn't sticking...
    @registry_patients.model = NodeNetBackbone.Models.RegistryPatient
    # TODO: Try to only round trip once on initial load
    # @registry_patients.reset($('#container_data').attr('data'))
    @registry_patients.fetch()

    # TODO: SSI - why are the routes not getting processed?
    this.index()

  index: ->
    console.log 'made it to the route index'
    view = new NodeNetBackbone.Views.RegistryPatients.Index(collection: @registry_patients)
    # $('#container').html('<h1>Patients V3: (Backbone):</h1>')
    $('#container').html(view.render().el)

【问题讨论】:

  • 你能举一些例子来说明你是如何定义你的路线的吗?
  • 没有代码示例,我们无法看到可以修复的问题,因此请提供您的代码
  • 好吧,我只是预感到一下,但是,默认路由不是'*.'。只是''(一个空字符串)。

标签: node.js backbone.js coffeescript


【解决方案1】:

主干路由不是正则表达式(除非您使用route 手动添加正则表达式路由)。来自fine manual

路由可以包含参数部分,:param,它匹配斜杠之间的单个 URL 组件;和 splat 部分*splat,可以匹配任意数量的 URL 组件。

[...] "file/*path" 的路由将匹配 #file/nested/folder/file.txt,将 "nested/folder/file.txt" 传递给操作。

如果我们检查来源,we'll see this:

// Backbone.Router
// -------------------
//...
// Cached regular expressions for matching named param parts and splatted
// parts of route strings.
var namedParam    = /:\w+/g;
var splatParam    = /\*\w+/g;

所以你的'.*' 路由应该只匹配文字'.*',而不是匹配你所期望的“任何东西”。

我想你想要更多这样的东西:

routes:
  ''          : 'index'
  #...
  '*path'     : 'index'

确保您的*path 路线位于the bottom of your route list

// Bind all defined routes to `Backbone.history`. We have to reverse the
// order of the routes here to support behavior where the most general
// routes can be defined at the bottom of the route map.

这个关于对象中元素“顺序”的假设在我看来是相当危险且考虑不周的there is no guaranteed order

未指定枚举属性的机制和顺序(第一个算法中的步骤 6.a,第二个算法中的步骤 7.a)。

我认为你最好在 initialize 方法中手动添加默认的 *path 路由:

class NodeNetBackbone.Routers.RegistryPatients extends Backbone.Router
  routes:
    ''          : 'index'
    '/index'    : 'index'
    '/:id'      : 'show'
    '/new'      : 'new'
    '/:id/edit' : 'edit'

  initialize: ->
    console.log 'init the router'
    @route '*path', 'index'
    #...

【讨论】:

    猜你喜欢
    • 2017-11-16
    • 1970-01-01
    • 1970-01-01
    • 2016-01-20
    • 2012-03-09
    • 1970-01-01
    • 2016-06-29
    • 2015-07-17
    • 2020-02-20
    相关资源
    最近更新 更多