2013-02-18 23 views
1

緩衝區數組我使用$.when在其他邏輯之前運行2個函數。現在,在幾種情況下,我需要在執行相同的邏輯之前運行一組不同的函數,所以我想將一組函數傳遞給$.when,但無法運行。使用jQuery.when()

喜歡的東西:

function funcA(){ 
    console.log("funcA"); 
} 
function funcB(){ 
    console.log("funcB") 
} 
var funcArr = [funcA, funcB]; 

$.when(funcArr).then(function(){ 
    console.log("DONE!"); 
}); 

但是,這並不工作,並寫入控制檯的唯一事情就是「DONE!」。 我閱讀下列How do you work with an array of jQuery Deferreds?,但下面的行爲是一樣的:

$.when.apply($, funcArr).then(function(){ 
    console.log("DONE!") 
}); 

有什麼不對呢? 謝謝。

回答

3

您對$.when輸入是Deferred類型,這是該函數的預期輸入型的不 - http://api.jquery.com/jQuery.when/

最簡單地說,你可以構建Deferred類型與功能爲beforeStart施工參數。像:

var funcArr = [$.Deferred(funcA), $.Deferred(funcB)]; 

這裏的工作小提琴:http://jsfiddle.net/6MeM5/

此外:

如果你只是想在一個函數數組來執行各項功能,你不需要得到涉及Deferred。只需迭代陣列使用$.each,如:

$.each(funcArr, function(){ 
    this(); 
}); 
+0

很好,感謝您的迅速回復! – Haji 2013-02-18 07:34:49