Is there a way to fire a single function once when any event is raised?
For example, if I have the following function: (demo in jsfiddle)
To fire once and keep firing, the following snippet may be used:
https://jsfiddle.net/wo0r785t/1/
$.fn.onSingle = function(events, callback){
if ("function" == typeof(callback)) {
var t = this;
var internalCallback = function(event){
$(t).off(events, internalCallback);
callback.apply(t, [event]);
setTimeout(function(){
$(t).on(events, internalCallback);
}, 0);
};
$(t).on(events, internalCallback);
}
return $(this);
};
It works by temporarily disabling the events using the internalCallback
function, and asynchronously (setTimeout
) enabling it again.
Most other suggestions in this thread disable all future events on the target. However, while OP seems satisfied with previous answers, his question does not mention the permanent disabling of events.