【问题标题】:How to initialize multiple routers?如何初始化多个路由器?
【发布时间】:2016-12-20 03:00:08
【问题描述】:

我在Routers 中有两个资源:StudentsColleges

class App.Routers.Colleges extends Backbone.Router
  routes:
   "index": 'index'
class App.Routers.Students extends Backbone.Router
  routes:
   'index': 'index'
   'new': 'newStudent'

如何初始化这两条路由以使其正常工作?

我尝试像下面的代码一样初始化,但它不起作用。

window.App =
 Models: {}
 Collections: {}
 Views: {}
 Routers: {}
 initialize: ->
   new App.Routers.Students
   new App.Routers.Colleges
   Backbone.history.start()
 $(document).ready ->
   App.initialize()

当我尝试运行上述代码时,它只向我显示new App.Routers.Colleges 中的大学和学生 div 中的数据。

【问题讨论】:

    标签: javascript backbone.js coffeescript backbone-routing


    【解决方案1】:

    路由器中的路由被添加到全局Backbone.history 对象中。因此,任何相同的路线都会覆盖先前的路线。如果在之后定义,即使不相同的路由也可能会覆盖类似但更具体的路由。

    当实例化一个新路由器时,它的构造函数调用_bindRoutes,它会解析从最后一个到第一个的路由,因此应该首先定义特定的路由,然后定义更通用的路由,以任何包罗万象的路由结束。

    每个 URL 都必须是唯一的,因此您可以使用前缀为每个路由器命名:

    class App.Routers.Colleges extends Backbone.Router
      routes:
       'colleges': 'index'
    class App.Routers.Students extends Backbone.Router
      routes:
       'students/new': 'newStudent'
       'students': 'index'
    

    或者您可以使用(或自己制作)子路由器/控制器。

    【讨论】:

      猜你喜欢
      • 2012-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-09
      • 1970-01-01
      • 2015-12-11
      • 2013-08-11
      相关资源
      最近更新 更多