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 呼び出しが 1 つだけの場合は、次のようにします。

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 が指摘しているrenderように、正しいコンテキストで呼び出されるようにバインドする必要もあります (そうしないと、this内部renderではビュー オブジェクトではなく ajax オブジェクトが参照されます)。

_.bind(this.render, this);
于 2013-09-20T21:05:27.950 に答える