我正在使用“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.
关于javascript - 防止事件处理程序排队,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10985384/