我有一个主干视图,我想在 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 延迟 http://api.jquery.com/jQuery.Deferred/实施,具体而言$.when http://api.jquery.com/jQuery.when/。这允许您仅在多个异步操作完成时才采取操作。像这样使用它:
var ajax1 = team.fetch({ ... });
var ajax2 = goal.fetch({ ... });
$.when( ajax1, ajax2 ).done( this.render );
Edit
正如@muistooshort 指出的,你还必须绑定render
,以便使用正确的上下文调用它(否则this
inside render
将引用 ajax 对象而不是视图对象):
_.bind(this.render, this);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)