2012-06-17 47 views
7

我將應用分成幾個應用。如何使用backbone和requirejs定義/使用多個路由

main.js 
app.js 
app1/ 
    |- routing 
    |- controller 
    |- app 
app2/ 
    |- routing 
    |- controller 
    |- app 

1)當我嘗試使用路由器app1,他們的工作。
2)當我嘗試使用app2中的路由器時,它們不起作用。
3)如果我在main.js中的行'js/app1/routing',註釋app2路由器工作。

爲什麼我會得到這種行爲?
是否有一些應用程序在github上使用多個路由和requirejs的例子?

謝謝。

這裏是我的代碼:


** ** main.js

define([ 
    'js/app', 
    'js/app1/routing', // the routers in this app work 
    'js/app2/routing' // the routers in this app do not work but 
         // if I comment the previous line (js/app1/routing',) 
         // they works 
], 
function (App) 
{ 
    "use strict"; 
    App.initialize(); 
}); 

** ** app.js

define([], 
function() 
{ 
    "use strict"; 
    var app = new Backbone.Marionette.Application(); 

    return app; 
}); 

* * 一個PP1/rotuing **

define(['backbone','app1/controller'], function(Backbone, controller) 
{ 
    "use strict"; 
    var Router = Backbone.Marionette.AppRouter.extend({ 

     appRoutes: { 
      '*defaults': 'index1' 
     } 

    }); 
    return new Router({ 
     controller: controller 
    }); 

}); 

** APP2/routing.js **

define(['backbone','app2/controller'], function(Backbone, controller) 
{ 
    "use strict"; 
    var Router = Backbone.Marionette.AppRouter.extend({ 

     appRoutes: { 
      'app2': 'index2' 
     } 

    }); 
    return new Router({ 
     controller: controller 
    }); 

}); 

回答

5

的問題可能是由其中路由器文件被加載的順序引起,並且路由器被創建。

骨幹的history對象負責執行路由。它在路由器實例化時收集所有路由器上定義的所有路由。然後它監視瀏覽器的URL以進行更改。當它看到一個變化時,它將採取第一條可用的匹配路線,並啓動一條路線,跳過其他任何路線。

當您定義了*defaults路線時,所有內容都與此相匹配。因此,如果首先加載此路線,則不會有其他路線被擊中。所以,你需要在你的路由參數中更加明確,以便這條路由不會一直打到,或者你需要確保這個路由器是最後加載的。

+0

感謝您的回答。事實上,如果我設置''':'index1'而不是''* defaults':'index1'',它就可以工作。再次感謝。 –

+0

@DerickBailey http://stackoverflow.com/questions/20017210/router-js-function-not-executed你能幫我在這裏:) – CodeGuru

+0

@DerickBailey它實際上似乎在實踐中,你所描述的相反是真實的:如果你使用某種catchall路由,它需要被加載_first_爲了其他更具體的路線工作。理想情況下,行爲將被指定,以便我們可以依靠它,無論如何。 –