2013-05-06 27 views
3

我正在使用requirejs工作在我的第一個項目上。我有一個路由器和一個視圖,我想在單擊一個項目時從視圖中訪問我的Router.navigate()方法。我使用CoffeeScript。我怎樣才能讓路由器全球?骨幹和Requirejs。如何從任何地方訪問我的中樞路由器

router.coffee:

define [ 
'jquery' 
'backbone' 
'application/views/mainView' 
'application/models/app' 
],($,Backbone,MainView,App)-> 
class Router extends Backbone.Router 
    routes: 
    'organisation': 'organisationScreen' 
    '*actions': 'organisationScreen' 

    constructor:() -> 
    super @routes 

    initialize:()-> 

    Backbone.history.start() #pushState: true 
    console.log " The Route Initialized" 

    organisationScreen:()-> 
    $('.slides').fadeOut() 
    $('.confBlock').removeClass('onshow') 
    $('.organisationsBlock').addClass('onshow') 

view.coffee

define [ 
'jquery' 
'backbone' 
'application/views/conferenceView' 
],($,Backbone,ConferenceView)-> 

class OrganisationView extends Backbone.View 

    #el: '#appcontainer' 

    tagName : 'li' 
    className : 'organisation' 

    events: 
    'click .org-item' : 'choice' 


    template : _.template($('#Organisation-template').html()) 

    initialize :()-> 
    ... 


    render:()-> 
    ... 

    choice:(ev)-> 
    # Call Router.navigate() 
+0

爲什麼不就叫'Backbone.history.navigate()'? – loganfsmyth 2013-05-06 15:21:34

+0

@loganfsmyth oooh,抱歉,您忘記以答案的形式發佈您的問題。 :) – Kato 2013-05-06 15:25:13

回答

5

所有Router::navigate所做的就是調用Backbone.history.navigate所以我只想使用。 Here is the source

choice: (ev)-> 
    Backbone.history.navigate(...); 
+0

謝謝,這工作正常 – user2354740 2013-05-06 22:45:50

2

我看到你的問題的三個選項:

  1. 通路由器鑑於構造和局部變量使用@options.router
  2. 讓兩個模塊之間循環依賴(檢查這個答案https://stackoverflow.com/a/16314250/329226
  3. 從視圖中觸發自定義導航事件並從路由器內收聽它
+0

我已經使用解決方案3,但我不喜歡它。 Backbone.history.navigate()工作正常。但解決方案2可以幫助我解決其他一些問題。非常感謝。 :) – user2354740 2013-05-06 22:49:23

4

只需將您的路由器與您在Backbone對象中需要的其他全局變量一起存儲即可。

在你的路由器初始化執行以下操作:

Backbone.application = {}; 
    Backbone.application.router = this; 

然後使用它是這樣的:

define(["backbone"], function (Backbone) { 
    Backbone.application.router.myaction(); 
});