繁体   English   中英

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

[英]jQuery: Determine whether multiple events have ALL been triggered?

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

例如:

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM