jQuery:确定是否触发了多个事件

jQuery: Determine whether multiple events have ALL been triggered?

本文关键字:事件 是否 jQuery      更新时间:2023-09-26

我在异步调用发生后使用自定义触发的事件,我需要一种方法来确定它们何时全部被触发。

例如:

var ajaxFunction1 = function(){
    $.ajax({
        url: "someUrl.html",
        complete: function(){
            //Ok, all done
            $(document).trigger('ajaxFunction1Finished')
        }
    })
}
var ajaxFunction2 = function(){
    $.ajax({
        url: "someUrl.html",
        complete: function(){
            //Ok, all done
            $(document).trigger('ajaxFunction2Finished')
        }
    })
}
var ajaxFunction3 = function(){
    $.ajax({
        url: "someUrl.html",
        complete: function(){
            //Ok, all done
            $(document).trigger('ajaxFunction3Finished')
        }
    })
}
ajaxFunction1();
ajaxFunction2();
ajaxFunction3();
jQuery
   .when( /* Whenever $(document) receives those three events */ )
   .done(function(){
      //Do something
   })

这可能吗?我想避免触发新事件只是为了得到一个返回 true。

触发器

有什么特别之处吗?

var oneDone = false;
var twoDone = false;
var threeDone = false;
function checkIfEverythingIsDone() {
   if (oneDone && twoDone && threeDone) {
     // everything is done and you may proceed
   }
}
var ajaxFunction1 = function(){
  $.ajax({
    url: "someUrl.html",
    complete: function(){
      oneDone = true;
      checkIfEverythingIsDone();
    }
  })
}
var ajaxFunction2 = function(){
  $.ajax({
    url: "someUrl.html",
    complete: function(){
      twoDone = true;
      checkIfEverythingIsDone();
    }
  })
}
var ajaxFunction3 = function(){
  $.ajax({
    url: "someUrl.html",
    complete: function(){
      threeDone = true;
      checkIfEverythingIsDone();
    }
  })
}
ajaxFunction1();
ajaxFunction2();
ajaxFunction3();

这可能会有所帮助 -

var requestCompletedArray = [];
/* assuming i have `n` ajax calls to make */
for(var i = 0; i < n; i++) {
    $.ajax({
        url: "someUrl.html",
        complete: callback
    })
}
/* my callback definition */
function callback(data) {
    if(requestCompletedArray.length < n-1) {
        requestCompletedArray.push(data.status);
        return;
    } else if(requestCompletedArray.length === n-1) {
        //do something, all requests are completed
    } else {
        return;
    }
}