Using the Underscore _.debounce () Method

I am trying to use UnderscoreJS and the _.debounce() method to stop the callback function to re-enable the keyup event. I do this because every time you start typing, an AJAX call will be launched, so it would be quite expensive to make a call for every character you enter (:

This is how I use the method:

 onTypeEvents : function(selector, callback) { return $(selector).on('keyup', function(event){ var that = $(this).val().trim(); switch(event.keyCode) { case 8: if(that !== '') { if(that.length >= 2) { return _.debounce(function() { callback.apply(that, [ that ]) }, 150); } else { return _.debounce(function() { callback.apply(null, [ null ]) }, 150); }; }; break; case 9: break; case 13: break; case 27: break; case 37: break; case 38: break; case 39: break; case 40: break; default: if(that !== '') { if(that.length >= 2) { return _.debounce(function() { callback.apply(that, [ that ]) }, 150); } else { return _.debounce(function() { callback.apply(null, [ null ]) }, 150); }; }; break; }; event.preventDefault(); event.stopPropagation(); }); }, 

But apparently this does not work, because nothing is exciting anymore, but if I remove this method, my code will work fine (: So what could be wrong? Am I doing it wrong or am I missing something?

+6
source share
1 answer

The idea is to cancel the keyup callback itself. Thus, your code only responds to the last user you entered before it stops typing. Sort of:

 $(selector).on('keyup', _.debounce(function (e) { switch (e.keyCode) { /* your code */ } }, 500)); 
+16
source

All Articles