javascript - 防止事件处理程序排队

标签 javascript jquery asp.net

我正在使用“One”连接点击处理程序。

Jquery 的“one”方法将连接一个事件处理程序并在第一次调用后将其分离,但似乎如果您单击得足够快,可能会有多个事件处理程序排队并导致回调运行超过一次。

例如:

$("#button").one("click", function () {

            //run logic

});

如何防止这种行为。我假设“One”将在第一次运行后分离处理程序,但是如果您在运行回调时单击该按钮,假设它将第二次运行是否合理?

最佳答案

I am assuming "One" will detach the handler after running it the first time

不正确,.one 将在运行处理程序函数之前分离事件处理程序。如果你看.one源代码中,.off 在调用处理函数之前触发。

if (one === 1) {
    origFn = fn;
    fn = function (event) {
        jQuery().off(event);  //Your event is unregistered here
        return origFn.apply(this, arguments); //Your handler is called
    };
    fn.guid = origFn.guid || (origFn.guid = jQuery.guid++);
}

正如 Frédéric Hamidi 在评论中指出的那样,

Even if the handler re-triggers the event during its execution, the actual handling of the new event will not occur until after the current handler has returned and the original event is fully resolved (possibly involving other handlers if the event is allowed to bubble up the DOM tree). By that time, the handler will have been removed in both cases.

证明: http://jsfiddle.net/skram/abcvW/2/

关于javascript - 防止事件处理程序排队,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10985384/

相关文章:

jquery - 上下文菜单与 jQuery FullCalendar 集成

c# - 我有一个为 ViewState 赋值的控件。它有效,但 ViewState 被禁用。如何?

c# - 连接没有像它应该的那样关闭

javascript - 为什么新数组慢?

jquery - 如何使用Jquery对每个匹配元素重复IF语句

javascript - jquery 上一个-下一个可见选择器

javascript - TubePlayer 插件视频当前时间与 jquery ui slider 同步

javascript - 如何更新对象属性的可枚举性?

javascript - bxSlider 从 ajax 加载幻灯片

javascript - 使用 angularJS 在 Ionic 应用程序中的两个页面之间传递值