I use jQuery and for things like setting toggles, I find myself writing a lot of code like:
foo.toggleSetting = function() {
var el = $(this);
if(el.data('clicked')) return false; //need to back off if we're already doing something
el.data('clicked',true);
var visible = $(this).is(':visible');
$.ajax({
url: '/update_setting',
data: {'status': visible},
success: function() { el.data('clicked',false); }
});
}
$(function(){
$('#setting_toggle').click(foo.toggleSetting);
});
What I’m trying to prevent is someone spamming a single settings toggle and sending a ton of requests to the server, but this just feels clunky. I know I could set the ajax request to synchronous mode, but that blocks the whole app from doing anything which is also not my intention (ie you could play with other toggles and that would be just fine).
How do other folks handle this type of situation?’
One way would be to use
.one()and on the success callback rebind the event.