我有一个主干视图,我想在2次异步调用后呈现html:
initialize: function (model, options) {
team.fetch({
success: function (collection) {
//do some things
});
goal.fetch({
success: function (collection) {
//do some things
});
this.render();
}
render: function () {
this.$el.html(template());
return this;
}
显然,使用上面的代码,html模板将在ajax调用之前/期间返回。通常,当只有一个ajax调用时,我会这样做:
initialize: function (model, options) {
var that = this;
team.fetch({
success: function (collection) {
//do some things
that.render();
});
}
render: function () {
this.$el.html(template());
return this;
}
用多个ajax调用执行此操作的最优雅的方法是什么?
我将特别使用JQuery Deferred实现$.when
。这使您仅在多个异步操作完成后才执行操作。像这样使用它:
var ajax1 = team.fetch({ ... });
var ajax2 = goal.fetch({ ... });
$.when( ajax1, ajax2 ).done( this.render );
编辑
正如@muistooshort指出的那样,您还必须绑定render
,以便使用正确的上下文调用它(否则,this
内部render
将引用ajax对象而不是view对象):
_.bind(this.render, this);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句