下面的代码模拟通过脱附函数执行实时搜索(用控制台输出代替)。
调用but函数,但不调用传递的liveSearch函数。我猜是因为debounce返回一个没有执行的函数。
我怎么能以这样一种方式调用liveSearch,以至于它实际上被取消了?
var MySearch = (function($) {
var $search = $('.search'),
searchDelay = 500,
keysToIgnore = [8, 16, 17, 18, 27, 32, 37, 38, 39, 40, 91, 191, 220]; // space, esc, bkspc, ctrl, alt, cmd, arrows, /\
function init() {
$search.on('keyup', function(e) {
if (keysToIgnore.indexOf(e.keyCode) == -1) {
// FIXME: this isn't actually executing the passed liveSearch fn
debounce(liveSearch, searchDelay);
// This executes liveSearch, but doesnt debounce
// debounce(liveSearch, searchDelay)();
}
});
}
function liveSearch() {
console.log("searching:", $search.val());
}
// Remy's debounce func:
// https://remysharp.com/2010/07/21/throttling-function-calls
function debounce(fn, delay) {
console.log("debouncing for", delay);
var timer = null;
return function () {
var context = this,
args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
fn.apply(context, args);
}, delay);
};
}
return {
init: init
};
}(jQuery));
jQuery(function() {
MySearch.init();
});http://codepen.io/bbodien/pen/BpWBXm?editors=0010
发布于 2017-01-19 17:33:52
debounce的每个调用都使用一个timer变量创建自己的闭包。因此,debounce函数设计为只调用一次,并返回一个应该调用的函数,而不是liveSearch。
function init() {
var debouncedLiveSearch = debounce(liveSearch, searchDelay);
$search.on('keyup', function(e) {
if (keysToIgnore.indexOf(e.keyCode) == -1) {
debouncedLiveSearch();
}
});
}https://stackoverflow.com/questions/41748091
复制相似问题