我正在尝试渲染一组项目。通常我会做的是这样的:
StuffView = Backbone.View.extend({
...
render: function(){
...
this.$el.html( ... );
return this;
}
...
});
StuffCollectionView = Backbone.View.extend({
...
render: function(){
this.collection.each(addOne, this);
},
addOne: function(stuff){
var view = new StuffView({model: stuff});
this.$el.append(view.render().el);
}
...
});
然而,这一次我正在构建一种不同类型的视图。每个 StuffView 的渲染都需要一些时间,所以我无法同步执行此操作。新 StuffView 的代码如下所示:
StuffView = Backbone.View.extend({
...
render: function(){
...
// Asynchronous rendering
SlowRenderingFunction(function(renderedResult){
this.$el.html(renderedResult);
});
}
});
在这种情况下,我不能只从渲染中返回它并将其结果附加到 StuffCollectionView 的 el 中。我想到的一个技巧是将回调函数传递给 StuffView 的渲染,并在完成渲染时让它回调。这是一个例子:
StuffView = Backbone.View.extend({
...
render: function(callback){
...
// Asynchronous rendering
SlowRenderingFunction(function(renderedResult){
this.$el.html(renderedResult);
callback(this);
});
}
});
StuffCollectionView = Backbone.View.extend({
...
initialize: function(){
_.bindAll(this, "onStuffFinishedRendering");
},
render: function(){
this.collection.each(addOne, this);
},
addOne: function(stuff){
var view = new StuffView({model: stuff});
view.render(onStuffFinishedRendering);
},
onStuffFinishedRendering: function(renderedResult){
this.$el.append(renderedResult.el);
}
...
});
但由于某种原因它不起作用。此外,这感觉太hacky并且感觉不对。是否有异步渲染子视图的传统方法?