gpt4 book ai didi

javascript - jQuery : fire callback only once

转载 作者:行者123 更新时间:2023-12-03 01:04:34 27 4
gpt4 key购买 nike

如何告诉 jQuery 仅触发一次回调函数?

$(document).on('ready turbolinks:load', function callback_function() {
console.log('callback function') // fired twice, on 'ready' and 'turbolinks:load' events
});

我希望在“ready”和“turbolinks:load”时调用callback_function,但如果两个事件发生在同一页面上,则不要调用两次。

编辑:我知道 jQuery one() 函数,它实际上并没有回答问题。根据 jQuery 文档,“处理程序最多针对每个事件类型的每个元素执行一次。”我想要相反:处理程序对所有事件类型执行一次。

最佳答案

您可以使用 jQuery.off 取消绑定(bind)回调并使用计数器来计算最大重复次数。与.one每个事件都会执行一次回调,这是不可取的

let count = 0;
function callbackWithCounter(event) {
if (count++ >= 1){
$(this).off(event)
return;
}
console.log("button clicked " + count);
}

function simpleCallback(event) {
console.log("button clicked");
}

$('#clickme').one("click mousedown mouseup", simpleCallback);
$('#clickme-two').on("click mousedown mouseup", callbackWithCounter);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='clickme'>Click me using .one</button><br/>
<button id='clickme-two'>Click me with a counter and .off</button>

您还可以创建一个辅助函数来管理这些有限生命周期的回调

//a wrapper that will ensure the callback "self-destructs" and will be unbound correctly
function makeSelfDestructingEventCallback(maxExecutions, callback) {
let count = 0;

return function(event) {
if (count++ >= maxExecutions){
$(this).off(event)
return;
}
//pass any normal arguments down to the wrapped callback
return callback.apply(this, arguments);
}
}

function callback(event) {
console.log("button clicked");
}

$('#clickme').on("click mousedown mouseup", makeSelfDestructingEventCallback(1, callback));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='clickme'>Click me</button>

这是同样的东西,采用柯里化(Currying)形式

//a curried wrapper that will ensure the callback "self-destructs" and will be unbound correctly
function makeSelfDestructingEventCallback(maxExecutions) {
return function(callback) {
let count = 0;
return function(event) {
if (count++ >= maxExecutions){
$(this).off(event)
return;
}
//pass any normal arguments down to the wrapped callback
return callback.apply(this, arguments);
}
}

}

function callback(event) {
console.log("button clicked");
}

let one = makeSelfDestructingEventCallback(1);
let two = makeSelfDestructingEventCallback(2);

$('#clickme').on("click mousedown mouseup", one(callback));
$('#clickme-two').on("click mousedown mouseup", two(callback));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='clickme'>Click me - single execution</button><br/>
<button id='clickme-two'>Click me - executes twice</button>

关于javascript - jQuery : fire callback only once,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52466684/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com