问题
I'm trying to use UnderscoreJS and it's _.debounce()
method to stop a callback function for firing repeatingly on keyup event. I'm doing that because each time you start typing, an AJAX call will be fired up so it would be quite expensive to make a call for each character you type (:
This is how I'm using 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 it doesn't work because nothing is firing up anymore, but if I remove the method my code works just fine (: So what could be going wrong in there ? Am I doing it wrong or am I missing something ?
回答1:
The idea is to debounce the keyup callback itself. That way your code only reacts to the last key your user typed before he stopped typing. Something like:
$(selector).on('keyup', _.debounce(function (e) {
switch (e.keyCode) {
/* your code */
}
}, 500));
来源:https://stackoverflow.com/questions/13158708/using-underscores-debounce-method