【问题标题】:_.throttle implementation using RXJS observables_.throttle 使用 RXJS observables 实现
【发布时间】:2016-12-03 17:42:31
【问题描述】:

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

在下划线中,我们使用以下行来做到这一点 -

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

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

【问题讨论】:

    标签: javascript underscore.js rxjs throttling


    【解决方案1】:

    只需使用throttle 运算符。

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

    它将限制事件,使得在单个 500 毫秒窗口内只能通过一个事件。

    【讨论】:

    • 赞赏。只是想澄清一下。 Rx.Observables.fromEvent 将监听事件(如 mousemove 此处)。如果我不想监听一个事件,我只想限制一个函数怎么办?我希望我的问题是有效的。如果不是请协助。就像我说的我想模仿以下函数的行为。 _.throttle(functionName, timespan, {trailing : true/false})
    • 您可以破解另一个答案所暗示的解决方案,但它并不是真正的“Rx”解决方案。我的问题是为什么它必须是一个函数?什么在调用该函数?通常使用 Rx 的想法是从源代码开始,围绕整个任务构建管道。
    【解决方案2】:

    看看 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>

    【讨论】:

    • 赞赏。但是有没有像 fromEvent 这样的方法,它将另一种方法作为输入并使用其他方法来限制它,比如说示例?
    • @PushkarKathuria 我并没有真正得到你想要的,但我编辑了我的答案,以便你可以看到与 RxJs 下划线实现类似的油门。如果有点击,它会每秒触发一次函数。
    • 它是否只适用于事件?如果听起来很愚蠢,请道歉。但我需要执行的任务只是限制函数调用。下面这行所做的相同:- _.throttle(function, timespan, {trailing : true/false}) 上面的行将在特定时间跨度内限制函数并在之后调用它。我希望我能够澄清这个问题?
    • 哦。抱歉,但我是新手。你能给我一个使用 .throttle 函数的例子吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-08
    • 2019-03-03
    • 2018-11-24
    • 1970-01-01
    • 1970-01-01
    • 2020-02-10
    相关资源
    最近更新 更多