jQuery同步触发自定义事件? [英] jQuery trigger custom event synchronously?

查看:97
本文介绍了jQuery同步触发自定义事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using the jQuery trigger method to call an event... but it behaves inconsistently. Sometimes it call the event, sometimes it does not.

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

自定义事件有很多听众添加到它。
就好像触发器方法不同步,允许在执行事件之前更改 window.location.href 。当window.location.href被更改时,会发生导航,中断所有内容。

The custom-event has lots of listeners added to it. It is as if the trigger method is not synchronous, allowing the window.location.href be changed before executing the events. And when window.location.href is changed a navigation occurs, interrupting everything.

如何同步触发事件?

使用jQuery 1.8.1。

Using jQuery 1.8.1.

谢谢!

编辑

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

I have found that the event, when called has a stack trace like this:


  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)

  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)

这证明jQuery 触发器方法是异步的。(我错了......这只能证明我正在调用的事件,里面有动画,并在动画后调用回调中的预期函数)

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

推荐答案

你,我的朋友,正在寻找jQuerywhen。

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

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

强迫任何事情成为同步,你可以使用这样的东西....

To force anything to be synchronous, you can use something like this....

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

这篇关于jQuery同步触发自定义事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆