How do you get jQuery to wait until a previous event is fired

I have a list of divs, whenever I click on them, I call a function, some run other ajax functions. Now, when the click even fires the ajax event, if I click on another div, I get the last div function called by the click. How to solve this problem.

document.addEventListener("click",function(event){
                checkparent(event);

    } 

function checkpaternt(event){

    if(($(event.target).class=="checkparent"){//call ajax functions
    }
    else {//call local functions}

later I check the class name for the purpose and call various functions. some more information (there are many div elements and if there are others) Thanks.

+4
source share
4 answers

Using a boolean flag: (and fixing the code)

function checkparent(event) {
    if (ajaxRequestOn) return;
    if (event.target.className == "checkparent") {
        ajaxRequestOn = true;
        //call ajax functions
        $.ajax( /* ...*/ ).always(function () {
            ajaxRequestOn = false;
        });
    } else {
        //call local functions
    }
}
+1
source

I think the following example may help you.

callbacks = [$.Deferred(), $.Deferred()];
    obj1.on('click', callbacks[0].resolve);
    obj2.on('click', callbacks[1].resolve);

    $.when(callbacks).done(function() { console.log('After to events done'); });

.

, .

, .done()

+1

, element.type ,

HTML

<input type="text" id="tipo-imovel" />

Script

$("#tipo-imovel").on("click change", function(event){
    alert(event.type + " is fired");
});

,

, ,

0

: jQuery. , :

jQuery

- ajax. SO , , , -

, AJAX. setTimeout , AJAX, ...

$('#elementId').click(function (e) {
  var $element = $(e.currenttarget);
  $element.queue('myqueue', function () {
    var $el = $(this);

    //Do stuff on $el

    //Remove this event from the queue and process next...
    $el.dequeue();
  });
});

:

  • click
  • 'myqueue'
  • , ​​ , - , jQuery 'this'.

, dequeue , window.setTimeout(500, function () { $this.dequeue(); });, 500 ...

jQuery

This function is similar to providing a callback function using animation, but does not require that the callback be indicated while the animation is running.

$( "#foo" ).slideUp(); $( "#foo" ).queue(function() {  
  alert( "Animation complete." );   
  $( this ).dequeue(); 
}); 

This is equivalent to:

$( "#foo" ).slideUp(function() {   
  alert( "Animation complete."
); }); 

Note that when adding a function with .queue (), we must make sure that .dequeue () is ultimately called so that the next function in the line is executed.

Update. The answer has been modified to include a working script and some explanation.

0
source

Source: https://habr.com/ru/post/1538377/


All Articles