jQuery同步触发自定义事件?

我使用jQuery触发器方法来调用事件……但它的行为不一致。 有时它会调用事件,有时则不会。

text 

custom-event添加了许多侦听器。 就好像触发器方法不是同步的,允许在执行事件之前更改window.location.href 。 当window.location.href被更改时,会发生导航,中断所有内容。

如何同步触发事件?

使用jQuery 1.8.1。

谢谢!

编辑

我发现这个事件在被调用时有一个像这样的堆栈跟踪:

  1. jQuery.fx.tick(jquery-1.8.1.js:9021)
  2. tick(jquery-1.8.1.js:8499)
  3. jQuery.Callbacks.self.fireWith(jquery-1.8.1.js:1082)
  4. jQuery.Callbacks.fire(jquery-1.8.1.js:974)
  5. jQuery.speed.opt.complete(jquery-1.8.1.js:8991)
  6. $ .customEvent(myfile.js:28)

这certificatejQuery trigger方法是异步的。 (我错了……这只certificate我正在调用的事件,里面有动画,并且在动画后调用回调中的预期函数)

你,我的朋友,正在寻找jQuery“when”。

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

要强制任何同步,你可以使用这样的东西….

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

阅读有关triggerHandler的文档:

.triggerHandler()不返回jQuery对象(允许链接),而是返回它导致执行的最后一个处理程序返回的任何值。 如果没有重新触发处理程序,则返回undefined

文档中的这一点让我认为像这样的代码:

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

会满足你的要求。

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