JQuery custom event triggered?

I use the jQuery trigger method to trigger an event ... but it behaves inconsistently. Sometimes it causes an event, sometimes it is not.

<a href="#" onclick=" $(this).trigger('custom-event'); window.location.href = 'url'; return false; ">text</a> 

A lot of listeners have been added to custom-event . It looks like the trigger method is not synchronous, which allows you to change window.location.href before the events are executed. And when window.location.href changes, navigation happens, interrupting everything.

How can I trigger events synchronously?

Using jQuery 1.8.1.

Thanks!

EDIT

I found that the event when the called one has a stack trace looks like this:

  • jQuery.fx.tick (jquery-1.8.1.js: 9021)
  • tick (jquery-1.8.1.js: 8499)
  • jQuery.Callbacks.self.fireWith (jquery-1.8.1.js: 1082)
  • jQuery.Callbacks.fire (jquery-1.8.1.js: 974)
  • jQuery.speed.opt.complete (jquery-1.8.1.js: 8991)
  • $. customEvent (myfile.js: 28)

This proves that the jQuery trigger method is asynchronous. (I was wrong ... this only proves that the event that I called had an animation inside it and caused the expected function inside the callback after the animation)

+7
source share
2 answers

You, my friend, are looking for jQuery "when."

http://api.jquery.com/jQuery.when/

To make something be synchronous, you can use something like this ....

 $.when($(this).trigger('custom-event')).done(function(){ window.location.href = 'url'; }); 
+24
source

Reading triggerHandler documentation:

Instead of returning a jQuery object (to enable the chain),. TriggerHandler () returns any value returned by the last handler that it called. If the handlers do not start, it returns undefined

This item in the documentation allows me to think that such code looks like this:

 // Trigger the custom event $(this).triggerHandler('custom-event'); // This code will only run when all events are run window.location.href = 'url'; 

meets your requirements.

See http://api.jquery.com/triggerHandler/

+9
source

All Articles