_.throttle 使用 RXJS observables 实现

_.throttle implementation using RXJS observables

我是 Rxjs Observables 的新手,我需要使用 Rxjs 实现节流。

在下划线中,我们使用以下行 -

_.throttle(functionName, timespan, {trailing : true/false}).

请协助如何使用 observables 做到这一点。

看看 RxJs 中的 sample 运算符

这是 div 上的 mousemove 事件的简单示例。

const source = document.getElementById('source');

Rx.Observable
  .fromEvent(source, 'mousemove')
  .sample(1000)
  .map(event => ({x: event.offsetX, y: event.offsetY}))
  .subscribe(console.log);
#source {
  width: 400px;
  height: 400px;
  background-color: grey;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.1.0/rx.all.js"></script>

<div id="source"></div>

如果你想使用 RxJS 实现节流,你可以这样做:

function throttle(fn, delay) {
  const subject = new Rx.Subject();
  
  subject
    .sample(delay)
    .subscribe(args => fn(...args));
  
  return (...args) => subject.onNext(args);
}

const sourceBtn = document.getElementById('source');
const countSpan = document.getElementById('count');
let count = 0;

sourceBtn.addEventListener('click', throttle(() => {
  count++;
                                             
  countSpan.innerHTML = count;
}, 1000));
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.1.0/rx.all.js"></script>

<button id="source" type="button">click</button> <br>
count = <span id="count"></span>

只需使用 throttle 运算符。

Rx.Observable.fromEvent(window, 'mousemove')
  .throttle(500)
  .subscribe(x => console.log(x));

它将限制事件,以便在单个 500 毫秒内只有一个事件可以通过 window。