2016-12-19 68 views
0

我有兩個資源RoutersStudentsColleges如何初始化多個路由器?

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兩個院校和學生股利。

回答

1

路由器中的路由被添加到全局Backbone.history對象。所以任何相同的路線都會覆蓋先前的路線。即使不相同的路線可能會覆蓋類似但更具體的路線(如果之後定義)。

當實例化一個新的路由器時,它的構造函數調用_bindRoutes,它解析從最後到第一個路由的路由,因此應該首先定義特定路由,然後定義更通用的路由,以任何全接收路由結束。

每個網址都必須是唯一的,所以你可以命名空間的每一個路由器用一個前綴:

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

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

相關問題