【发布时间】:2016-12-03 17:42:31
【问题描述】:
我是 Rxjs Observables 的新手,我需要使用 Rxjs 实现节流。
在下划线中,我们使用以下行来做到这一点 -
_.throttle(functionName, timespan, {trailing : true/false}).
请帮助如何使用 observables 做到这一点。
【问题讨论】:
标签: javascript underscore.js rxjs throttling
我是 Rxjs Observables 的新手,我需要使用 Rxjs 实现节流。
在下划线中,我们使用以下行来做到这一点 -
_.throttle(functionName, timespan, {trailing : true/false}).
请帮助如何使用 observables 做到这一点。
【问题讨论】:
标签: javascript underscore.js rxjs throttling
只需使用throttle 运算符。
Rx.Observable.fromEvent(window, 'mousemove')
.throttle(500)
.subscribe(x => console.log(x));
它将限制事件,使得在单个 500 毫秒窗口内只能通过一个事件。
【讨论】:
看看 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>
【讨论】: