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;
}