I am trying to utilize .off()
in my JS to handle turning off all clicking during an ajax request and then turning it back on once it is done. I know the code to use for that is ajaxStart().ajaxStop()
.
What I am running into is that my .on('click')
uses a nameless function to work. I.e.: $(document).on('click', '-enter-delegated-elements-here-', function (e) { // Click stuff here, like the click to run the ajax request });
This creates a problem when for when, after I have turned off my event listeners with .off
($(document).off('click', '**');
), I have to turn them back on. Unfortunately, plain $(document).on('click', '-enter-delegated-elements-here-');
does not work.
To demonstrate my point I have created this fiddle.
(a snippet is also here:)
$('add').on('click', '#add'); //here's the zinger!!!
var i = 0;
$('#add span').text(i);
$(document).on('click', '#add', function(e) {
$('#catcher').append(i);
i += 1;
$('#add span').text(i);
});
$(document).on('click', '#stop', function(e) {
if (!$(document).off('click', '#add')) {
$(document).off('click', '#add');
return;
}
$(this).text('Add five and re-enable catching');
i += 5;
$('#add span').text(i);
$('add').on('click', '#add'); //here's the zinger!!!
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="add">
Add to catcher: <span></span>
</button>
<button id="stop">
Stop catching
</button>
<h2>Catcher:</h2>
<div id="catcher"></div>
(While there is no ajax request, the principle is still the same)
I am aware that I could create a function to handle this, i.e.:
function forClicks(e) {
// Click stuff here, like the click to run the ajax request
}
$(document).on('click', '-enter-delegated-elements-here-', forClicks(e));
However, it becomes less practical to make a bunch of functions (like if you end up having multiple click handlers - to handle debouncers and whatnot, etc.) and also clutters up the global space when you could use nameless functions instead.
Does anyone know how I can turn back on an event handler which uses nameless functions, using
.on()
(after it has been turned off with.off()
)? Is there a way to do this or would it require another type of JS code (I am aware that.toggle()
does not work anymore, but maybe something like it?).