簡體   English   中英

如何進行兩個骨干獲取調用並將其組合

[英]How to make two backbone fetch calls and combine it

我需要在同一個集合上調用兩個后端調用,並將結果合並到單個集合對象中。 同樣,只有兩個獲取方法都成功后,我才需要觸發“同步”方法。

這是代碼片段

myCollection.fetch({ headers: {myheader: 'test1'}, data: {status: 'test1'}, reset: true});
myCollection.fetch({ headers: {myheader: 'test2'}, data: {status: 'test2'}, reset: true, add: true});

myCollection.once('sync error', function () {
    $('#js-my-grid').html(view.render().el);

}); 

我只需要在兩個提取都完成后才渲染視圖。 這怎么可能 ?

提前致謝。

如果可以的話,應該可以使用$ .when,只要其中之一失敗,它就會渲染視圖:

$.when(myCollection.fetch({ headers: {myheader: 'test1'}, data: {status: 'test1'}, reset: true}),
       myCollection.fetch({ headers: {myheader: 'test2'}, data: {status: 'test2'}, reset: true, add: true}))
 .always(function() {
     $('#js-my-grid').html(view.render().el);
 });

如果使用.done ,則可以分配將在兩個都成功時執行的回調,如果使用.fail ,則可以定義在兩個請求都失敗時將執行的回調。 我總是使用.always因為看起來您想渲染視圖無論請求是否成功。

var count = 0;

myCollection.fetch({..., success: _internal});
myCollection.fetch({..., success: _internal});

function _internal() {
    count ++;
    if (count < 2) return;
    //2 calls are finished. do whatever you want here.
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM