gpt4 book ai didi

jquery - 使用 Backbone 在多个异步 ajax 调用后渲染 View

转载 作者:行者123 更新时间:2023-12-01 00:14:26 25 4
gpt4 key购买 nike

我有一个主干 View ,我想在 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 指出的,您还必须绑定(bind) render,以便使用正确的上下文调用它(否则 render 内的 this > 将引用 ajax 对象而不是 View 对象):

_.bind(this.render, this);

关于jquery - 使用 Backbone 在多个异步 ajax 调用后渲染 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18925792/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com