2013-01-19 32 views
0

對不起,標題有點混亂。在主幹初始化回調之前不渲染路由

我的骨幹路由器具有以下結構:

var AppRouter = Backbone.Router.extend({ 
    routes: { 
     'notes': 'showNotes', 
     'news': 'showNews' 
    }, 
    showNews: function() { 
     // make view object and render 
    }, 
    showNotes: function() { 
     // make view object and render 
    }, 
    initialize: function() { 
     this.user.fetch({success: function(){ 
      // callback function 
     }}); 
    } 
}); 

我遇到的問題是,我需要將用戶傳入的意見,所以我需要每個渲染只運行,如果成功的回調中運行初始化。基本上我不想初始化完成,直到回調被調用。我無法弄清楚如何才能做到這一點。

感謝

回答

2

Router#initialize,在默認情況下,是一個空函數。在運行的時候,路線已經被移交給History,你可能已經通過了任何「乾淨」的方式來阻止它們。

如果你真的需要確保你的用戶是獲取路由器開始渲染之前,你可以做到這一點通過取得user的歷史開始,這樣的事情之前:

// in some initializer: 
    user.fetch({success: function() { 
    var router = new AppRouter({user: user}); 
    Backbone.history.start(); 
    }}); 

    // and your router: 
    initialize: function(options) { 
    if (options) this.user = options.user; 
    } 

但讓視圖響應被抓取的用戶也可能是有意義的,而不是確保它被事先加載。視圖可能只是在用戶加載之前不呈現任何內容,或者可能會顯示「加載」圖形等。在這種情況下,您只需:

// in your router 
showNotes: function() { 
    // note sure how you're storing your views, but for example: 
    this.currentView = new ShowNotesView({model: this.user}).render(); 
}, 

initialize: function() { 
    this.user.fetch(); 
} 

// and in the view 
initialize: function() { 
    this.model.on('sync', this.render.bind(this)); 
}, 

render: function() { 
    // note that `hasBeenSynced` is a made up property. Fill it in with something 
    // that indicates the model has been fetched successfully. Alternatively you 
    // might do this in the template. Lot of flexibility here. 
    if (this.model.hasBeenSynced) { 
    // render the model 
    } else { 
    // show nothing, a loading template, etc 
    } 
    return this; 
} 
+0

這是完美的。謝謝 –