Javascript 在初始化中回调之前不在主干中渲染路由
对不起,标题有点混乱 我的主干路由器具有以下结构:Javascript 在初始化中回调之前不在主干中渲染路由,javascript,model-view-controller,backbone.js,Javascript,Model View Controller,Backbone.js,对不起,标题有点混乱 我的主干路由器具有以下结构: var AppRouter = Backbone.Router.extend({ routes: { 'notes': 'showNotes', 'news': 'showNews' }, showNews: function() { // make view object and render }, showNotes: function() {
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
}});
}
});
我遇到的问题是,我需要将用户传递到视图中,因此我需要仅在成功回调在initialize内部运行时才运行每个渲染。基本上,我不希望在调用回调之前完成初始化。我想不出我怎样才能做到这一点
谢谢路由器#初始化
,默认为空函数。在它运行时,路由已经被传递到历史
,您可能已经通过了任何“干净”的方法来阻止它们
如果确实需要确保在路由器开始渲染之前提取您的用户,可以通过在历史开始之前提取用户来实现,如下所示:
// 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;
}
这太完美了。非常感谢。