4

我有一个主干视图,我想在 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 调用执行此操作的最优雅的方法是什么?

4

2 回答 2

3

我会使用JQuery Deferred实现,特别是$.when. 这使您仅在完成多个异步操作时才采取行动。像这样使用它:

var ajax1 = team.fetch({ ... });
var ajax2 = goal.fetch({ ... });

$.when( ajax1, ajax2 ).done( this.render );

编辑

正如@muistooshort 指出的那样,您还必须 bind render,以便使用正确的上下文调用它(否则this内部render将引用 ajax 对象而不是视图对象):

_.bind(this.render, this);
于 2013-09-20T21:05:27.950 回答
1

Just so you can appreciate what jQuery Deferred is saving you from, this is an example of how you'd solve this very common problem without it. (Imagine writing this same code for 4 collections/models, not just 2.)

initialize: function(model, options) {
    team.fetch();
    goal.fetch();

    this.listenTo(team, 'sync', this.teamFetched);
    this.listenTo(goal, 'sync', this.goalFetched);
},

teamFetched: function() {
    this._teamFetched = true;
    // if goal also fetched, call & return this.render()
    return (( this._goalFetched ) ? this.render() : this);
},

goalFetched: function() {
    this._goalFetched = true;
    // if team also fetched, call & return this.render()
    return (( this._teamFetched ) ? this.render() : this);
}

render: function() {
    this._goalFetched = this._teamFetched = false;

    this.$el.html(template());
    return this;
}
于 2013-09-20T22:26:52.987 回答