是否有更清晰的方法来去抖方法?

时间:2016-10-06 09:21:50

标签: javascript angular lodash

使用内联代码的_.debounce方法有更简洁的方法吗?还是总是需要3个步骤?

@Component({
template: `
  <div (mousemove)="onChanged($event)">
  </div>
`
})
export class MyClass {

  @Output() somethingChanged: EventEmitter<string> = new EventEmitter<string]>();

  constructor(){}

  // 1. define method
  triggerChanged = ()=>{
    this.somethingChanged.emit("changed!");
  }

  // 2. debounce method
  debouncedTriggerChanged = _.debounce( this.triggerChanged, 500);

  onChanged(){
      // 3. call debounced method
      this.debouncedTriggerChanged()
  }
}

1 个答案:

答案 0 :(得分:2)

这种方法怎么样 - 完全保留你建议的方法:

import { fromEvent } from 'rxjs/observable/fromEvent';
import { timer } from 'rxjs/observable/timer';
import { debounce } from 'rxjs/operators';

// ...

constructor(private elementRef: ElementRef) {
    const eventStream = fromEvent(elementRef.nativeElement, 'mousemove')
                            .pipe(debounce(() => timer(500)));

    eventStream.subscribe(input => this.somethingChanged.emit("changed!"));
}

2018-06-19:已更新至当前的RxJS版本