【问题标题】:jQuery : fire callback only oncejQuery:只触发一次回调
【发布时间】:2018-09-23 13:42:00
【问题描述】:
如何告诉 jQuery 只触发一次回调函数?
$(document).on('ready turbolinks:load', function callback_function() {
console.log('callback function') // fired twice, on 'ready' and 'turbolinks:load' events
});
我希望 callback_function 在“准备好”、“turbolinks:load”时被调用,但如果两个事件都发生在同一页面上,则不会调用两次。
编辑:我知道 jQuery one() 函数,它实际上并没有回答问题。根据 jQuery 文档,“每个事件类型的每个元素最多执行一次处理程序。”我希望反过来:对所有事件类型执行一次处理程序。
【问题讨论】:
标签:
javascript
jquery
ruby-on-rails
ruby-on-rails-5
【解决方案1】:
您可以使用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>