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

时间:2013-09-20 18:53:48

标签: javascript jquery ajax asynchronous

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

例如:

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
   })

这可能吗?我想避免触发新事件只是为了获得一个真实的回报。

2 个答案:

答案 0 :(得分:0)

这可能会有所帮助 -

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;
    }
}

答案 1 :(得分:0)

触发器有什么特别之处吗?

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();