首先 - 我是 MarionetteJS 菜鸟。
我在获取 ItemView 时无法显示加载消息或 throbber。当这个 ItemView 是从 Backbone 历史中的深层链接显示时,这尤其成问题(即 ItemView 是自用户直接链接到它后显示的应用程序的第一页)。我想指示页面正在加载(获取),最好使用简单的视图,然后使用获取的模型显示真实的模板化视图。
我在 SO 上看到了其他答案,例如 Marionette.async(已被弃用)并在 ItemView.initialize() 期间更改模板。
有人(Derrick?)在这里有任何建议或最佳实践吗?
更新:
我使用 collection.get(id) 从集合中获取模型,而不是直接使用 model.fetch()。
考虑到这一点,真正的问题是应该在哪里实现:
更新2:这就是我最终得到的,以防其他人想要这个解决方案:
app.ModelLayout = Backbone.Marionette.Layout.extend({
constructor: function(){
var args = Array.prototype.slice.apply(arguments);
Backbone.Marionette.Layout.prototype.constructor.apply(this, args);
// we want to know when the collection is loaded or changed significantly
this.listenTo(this.collection, "reset sync", this.resetHandler);
},
resetHandler: function () {
// whenever the collection is reset/sync'ed, we try to render the selected model
if (this.collection.length) {
// when there is no model, check to see if the collection is loaded and then try to get the
// specified id to render into this view
this.model = this.collection.get(this.id);
}
this.render();
},
getTemplate: function(){
// getTemplate will be called during render() processing.
// return a template based on state of collection, and state of model
if (this.model){
// normal case: we have a valid model, return the normal template
return this.template;
} else if (this.collection && this.collection.isSyncing) {
// collection is still syncing, tell the user that it is Loading
return this.loadingView;
} else {
// we're not syncing and we don't have a model, therefore, not found
return this.emptyView;
}
}
});
以下是如何使用它:
// display a single model on a page
app.Access.Layout.CardLayout = app.ModelLayout.extend({
regions: {
detailsRegion:"#detailsRegion",
eventsRegion:"#eventsRegion"
},
template:"CardLayout", // this is the normal template with a loaded model
loadingView:"LoadingView", // this is a template to show while loading the collection
emptyView:"PageNotFoundView", // this is a template to show when the model is not found
onRender : function() {
this.detailsRegion.show( blah );
this.eventsRegion.show( blah );
}
});
谢谢!