jQuery:只触发一次回调



如何告诉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 并使用计数器来取消绑定回调,以获得最大重复次数。使用.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>

这是咖喱形式的相同事情

//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>