1

I would like to update a model when the slider change event is triggered + a debounce time (in order to not stressing too much the layout, since that model is going to be used in a massive chart refreshed every 250ms).

This is the scenario:

HTML

    <kendo-slider [min]="1" 
                  [max]="5" 
                  [(ngModel)]="model" 
                  (valueChange)="functionToBeDebounced($event)">
    </kendo-slider>

TS

 public functionToBeDebounced(value) {
        this.model = value;
        this.notification.emit(this.model);
 }

Is it possible to do something like this?

    <kendo-slider [min]="1" 
                  [max]="5" 
                  [(ngModel)]="model" 
                  (valueChange)="functionToBeDebounced($event)"
                  [debounce]="500" >
    </kendo-slider>

The result would be calling functionToBeDebounced only when the sliding is over.

Dyd666
  • 705
  • 1
  • 11
  • 30

1 Answers1

3

You can use rxjs/Subject to debounce everything you want.

import { Subject } from 'rxjs/Subject';

private debouncer: Subject<any> = new Subject();

ngOnInit(){
  this.debouncer.debounceTime(500).subscribe(event => {
    this.functionToBeDebounced(event);
  });
}

private callDebouncer(event){
  this.debouncer.next(event);
}

(valueChange)="callDebouncer($event)"
Ploppy
  • 14,810
  • 6
  • 41
  • 58
  • Works fine, thanks! Totally forgot about reactive approach ;) – Dyd666 Mar 16 '17 at 14:38
  • Can you make a more generic approach ? For example if you have more than 1 control that requires debouncing. – Misi Feb 09 '18 at 13:03
  • @Misi Either use one debouncer for each control or only 1 debouncer but keep track of which control is used within the `callDebouncer` function. – Ploppy Feb 09 '18 at 13:08
  • @Ploppy For using only one debouncer, how would you track witch control needs debouncing ? private callDebouncer(control, event) { switch(control) { case "slider1": .. } } ?? – Misi Feb 09 '18 at 13:24
  • 1
    @Misi $event contains the html element, you could by example identify the controls with their id tag. Then in the `callDebouncer` function, save the active control in a variable (declared in the component). Then in the `subscribe` method you know which control is currently used and with a switch/case you will be able to do whatever you want. I'm not sure if it's the right way to do it, but it should work. – Ploppy Feb 09 '18 at 14:06