0

我一直在通过使用来研究 Jquery 的承诺when,我想知道它是否能够满足我的场景,或者我是否需要重新考虑我是如何做事的。

所以我有一个带有几个听众的backbone.js模型,例如:

this.on('supplier:change', function(){
    $.get('/supplier_details', function(data){
        // fill in some fields here
        anotherAjaxCallInAnotherFunction();
    });
});

anotherAjaxCallInAnotherFunction: function(){
    // Another Ajax call
}

如果我这样使用whenmodel.set({supplier: 'ss'}).done();promise 是否能够等到所有 Ajax 调用结束?

如果我在我的主干模型中设置需要多个 Ajax 调用的多个属性怎么办?承诺会封装模型的整个设置吗?

4

2 回答 2

1

One thing I didn't realise until I actually tried this was that you CAN chain Ajaz calls in this way, you just need to be a bit creative with your coding.

The easiest way to chain these sort of calls is like so:

this.on('supplier:change', function(){
    return $.get('/supplier_details').then(function(data){
        return anotherAjaxCallInAnotherFunction();
    });
}

function anotherAjaxCallInAnotherFunction(){
    return $.ajax();
}

And just chaining the deferred object like this will allow you to not only make the calls async but also do it without locking the browser thread.

You can find more info here: http://api.jquery.com/jQuery.Deferred/

于 2013-04-17T08:33:03.273 回答
0

你可以试试:

$.when( firstAjaxCall, secondAjaxCall )
  .done( 
      function(firstResp) { console.log(firstResp); },  
      function(secondResp) { console.log(secondResp); } 
  ); 

或者你可以listenTo是一个sync事件,当成功返回时firstAjaxCall,你可以调用secondAjaxCallBackbone Events

"sync" (model, resp, options) — 当模型(或集合)与服务器成功同步时。

于 2013-03-27T09:52:28.653 回答