使用 Underscore 的 _.debounce() 方法 [英] Using Underscore's _.debounce() method
问题描述
我正在尝试使用 UnderscoreJS 和它的 _.debounce()
方法来停止回调函数以在 keyup 事件上重复触发.我这样做是因为每次您开始输入时,都会触发 AJAX 调用,因此为您输入的每个字符进行调用会非常昂贵 (:
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 ?
推荐答案
这个想法是让 keyup 回调本身去抖动.这样您的代码只会对您的用户在停止输入之前输入的最后一个键做出反应.类似的东西:
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));
这篇关于使用 Underscore 的 _.debounce() 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!