Der folgende Code simuliert die Ausführung einer Live-Suche (ersetzt durch die Konsolenausgabe) über eine debounce function.Die Live-Suche in Javascript wurde debuggt, die Ausführung wird nicht ausgeführt.
Die Entprellfunktion wird aufgerufen, aber die übergebene liveSearch
Funktion ist nicht. Ich schätze, weil debounce
eine Funktion zurückgibt, die nicht ausgeführt wird.
Wie kann ich liveSearch
so anrufen, dass es tatsächlich entprellt wird?
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
[Eine weitere Entprellung Methode] (https://github.com/JDMcKinstry/debounce) – SpYk3HH