I am making a search on type Lightning Component for Salesforce.
I made a debounce function to check if a user stops typing, which does the delay successfully. However the function that runs in my debounce function will not accept an event now and a console.log(event)
says 'undefined'. I am not sure how to fix this error. My code is below...
debounce(func, wait, immediate) {
var timeout;
return function executedFunction() {
var context = this;
var args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}
termChange(evt) {
this.rows = [];
this.searchTerm = evt.target.value;
this.getCases();
}
handleTermChange = this.debounce(evt, function(){
this.termchange();
}, 2000, false)
When I used to just call termChange, It would search every key press and you would end up with duplicates, or unwanted records. Now with debounce it delays, but I can't find a way to pass the event in. (this.getCases()
is another function I created that retrieves the records.) Any ideas on how to do this?
First, the debounce
function takes a function as the first argument and you are trying to call it with event object. Second, termChange
is camel cased but inside the debounce call is is all lowercase, so this code would not run anyways.
Now, let's take a close look at what debounce
does. It takes a function and then returns another function that expects the same exact arguments. So if you just do:
handleTermChange = debounce(termChange)
then you should get a function that would take the event as it's first argument. To be safe, I would bind it to whatever "this" you use in your example and then it should be good to go