2017-05-08 56 views
0

我知道如何將功能附加到事件或甚至多個事件,我用這樣的代碼:JQuery的對多個事件

$(document).off('types_loaded').on('types_loaded',function(e,types){ 
    display_types(types); 
}); 

而且別的地方我這樣做:

$(document).trigger('types_loaded',types); 

變量類型從ajax調用中加載。

一切工作正常,但我不知道如何等待兩個或兩個以上的事件,是這樣的:

$(document).on('types_loaded' **AND** 'other_loaded',function(e,types,other){ 
    display_types(types); 
    display_other(other); 
}); 

和變量類型其他從兩個不同的Ajax調用正在添加。我正在學習選項,還是有任何其他方式來做這樣的事情?

回答

3

由於上jQuery.on的第一屬性枚舉就像一個OR條件(它會火的時候,任何事件的發生),則可以通過跟蹤什麼事件的變換行爲AND已經發生了,就像這樣:

window.eventHappened = {}; 
 
$(document).on('types_loaded other_loaded',function(e){ 
 
    console.log(e.type); 
 
    window.eventHappened[ e.type ] = 1; 
 
    if (typeof window.eventHappened['types_loaded'] != 'undefined' && typeof window.eventHappened['other_loaded'] != 'undefined') 
 
    { 
 
    // both happened 
 
    console.log('both happened'); 
 
    } 
 
}); 
 

 
$(document).trigger('other_loaded'); 
 
$(document).trigger('types_loaded');
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>

+0

如果我明白,第一個參數** **é有一個類型屬性,其中包含引發事件的事件的名稱,對嗎?如果這是真的,當兩個事件都完成時,很容易在任何事件和其他功能上觸發一個功能。非常感謝。 –

+0

的確,你完美無缺,情況就是如此! –

2

如果你的函數,使AJAX調用返回的承諾,你可以使用$.when

function getTypes() { 
    return $.ajax(// etc.) 
} 

function getOther() { 
    return $.ajax(// etc.) 
} 

$.when(getTypes(), getOther()).done(function (typesResult, otherResult) { 
    // Both calls have completed 
}); 

如果您需要更多的控制,並希望創建自己的諾言,你可以手動解決/拒絕當AJAX響應返回:

function getTypes() { 
    // This deferred object will return a promise immediately at the bottom of 
    // this function 

    var dfd = $.Deferred(); 

    $.ajax(// etc.) 
     .done(function(data) { 
      dfd.resolve(data); 
     }) 
     .fail(function() { 
      dfd.reject('Error'); 
     }); 

    // This promise returns to the caller immediately 

    return dfd.promise(); 
    } 

function getOther() { 
    // Same as above 
} 

$.when(getTypes(), getOther()).done(function (typesResult, otherResult) { 
    // Both calls have completed 
}); 
+0

謝謝,這個概念很明確,但是說_Jake AJAX call_的部分有點不清楚,但我正在研究這本手冊。 –

+0

不客氣。我更新了更多細節的例子。 –