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