I am trying to implement debouncing in angular, I know it provides a debounceTime rxjs operator, but I want to implement it from scratch. So when I use below debounce function.
debounce(func: Function, limit = 500) {
let timer: any;
return function () {
let context = this;
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(context, arguments);
}, limit);
}
}
I have a Search Function which uses a injected service(ExerciseService) to make an api call
search(query: string) {
this.exerciseService.searchExercises(query).subscribe(exercises => {
this.exercises = exercises;
});
}
I am calling the search method like this
optimizedSearch = this.debounce(search, 500);
The optimizedSearch method is binded to a click event in the template like this
<div class="search">
<input type="text" placeholder="Search..." (keyup)="optimizedSearch($any($event).target.value)()">
<button (click)="optimizedSearch($any($event).target.value)()">Search</button>
</div>
So now what's happening is that the value of 'this' keyword in the search method is being 'undefined'. Seems that there might be some context issue.
Can someone help me fix this? Thanks in advance
My component looks like this
import { Component, OnInit } from '@angular/core';
import { ExercisesService } from '../exercises.service';
@Component({
selector: 'app-exercises',
templateUrl: './exercises.component.html',
styleUrls: ['./exercises.component.css']
})
export class ExercisesComponent implements OnInit {
constructor(private exerciseService: ExercisesService) { }
ngOnInit(): void {
}
search(query: string) {
this.exerciseService.searchExercises(query).subscribe(exercises => {
this.exercises = exercises;
});
}
debounce(func: Function, limit = 500) {
let timer: any;
return function () {
let context = this;
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(context, arguments);
}, limit);
}
}
optimizedSearch = this.debounce(search, 500);
}