0

I'm having trouble with the way javascript execute the code (async)

I have this small piece of code that will trigger events and check the value of 'valid'.

My problem is that 'valid' is always true when entering the if statement because the events have not finished processing yet :

valid = true;

$(this).find('input').trigger('blur');
//valid will be modified in the triggered events

if(valid){
    //Do something
}

So I'd like to wait till the events are finished to enter the statement, but trigger doesn't take a callback

I have seen some questions about this already solved but I didn't understand them and how to implement them.

What should I use to solve this ?

Tofandel
  • 3,006
  • 1
  • 29
  • 48
  • 1
    Where's the code that gets executed when the input is blurred? – j08691 Mar 13 '15 at 16:27
  • 1
    [Is this related/a duplicate?](http://stackoverflow.com/questions/13338484/jquery-trigger-custom-event-synchronously) In theory it should be synchronous, so yes - we need to see your `blur` handler. – James Thorpe Mar 13 '15 at 16:27
  • 1
    What is `$(this)`? why don't you just have an event function - `$('input').on('blur', function(){});` – Adjit Mar 13 '15 at 16:28
  • No need to use trigger. You can directly use blur on element. It's better to post more code for helping. – hamed Mar 13 '15 at 16:32
  • @Adjit $(this) is a form, I'm inside a function that's just why I used $(this) – Tofandel Mar 13 '15 at 16:32
  • @JamesThorpe Yes, this solved my problem, when I used the jquery '$.when' it became synchronous, but it wasn't before, thanks – Tofandel Mar 13 '15 at 16:35
  • So why not show us the whole function so we can better understand the scope? your `trigger('blur')` is adding an event trigger for your form - but that is different than capturing the event – Adjit Mar 13 '15 at 16:38

3 Answers3

0

Thanks to JamesThorpe I found the answer I was looking for :

 valid = true;
 $.when($(this).find('input').trigger('blur')).done(function(){
     if(valid){
         //Do something
     }
 });

And now the if statement only gets executed after the events are triggered

Tofandel
  • 3,006
  • 1
  • 29
  • 48
0

As you want to have it triggered on blur, you can do it like this:

$(this).find('input').on('blur', function(){
    if(valid){
        //Do something
    }
});

Note that the function will be triggered on all blur events. To have it only once use .one()

Salil Dabholkar
  • 622
  • 3
  • 7
0

I don't understand why you are using trigger. I think you can directly use blur event:

$(this).find('input').blur(function(){
    if(valid)
      //do something
});
hamed
  • 7,939
  • 15
  • 60
  • 114