代码之家  ›  专栏  ›  技术社区  ›  feerlay

RXJS-检测长鼠标下降

  •  2
  • feerlay  · 技术社区  · 7 年前

    我想知道什么时候 mousedown 被解雇超过500米,如果是的-做点什么。我的尝试:

    const button = document.querySelector('button')
    const stream = Rx.Observable.fromEvent(button, 'mousedown')
    const mouseUp$ = Rx.Observable.fromEvent(button, 'mouseup')
    stream.delay(500).takeUntil(mouseUp$).subscribe(() => console.log(1))
    

    它起作用,但只在第一次运行时起作用然后,由于 takeUntil 接线员。如何让它每次都起作用?

    DEMO

    1 回复  |  直到 7 年前
        1
  •  3
  •   SplitterAlex    7 年前

    启动一个 TimerObservable 每500米 mouseDown$ 事件如果 mouseUp$ 500米内被解雇 unsubscribe 可计时 是的。

    const button = document.querySelector('button')
    const mouseDown$ = Rx.Observable.fromEvent(button, 'mousedown')
    const mouseUp$ = Rx.Observable.fromEvent(button, 'mouseup')
    
    const stream$ = mouseDown$.switchMap(() => Rx.Observable.TimerObservable(500).takeUntil(mouseUp$));
    
    stream$.subscribe(() => console.log('Only Fired after 500ms'))

    RxJS=6.0.0

    import { switchMap, takeUntil } from 'rxjs/operators';
    import { timer, fromEvent } from 'rxjs';
    
    const button = document.querySelector('button')
    const mouseDown$ = fromEvent(button, 'mousedown')
    const mouseUp$ = fromEvent(button, 'mouseup')
    
    const stream$ = mouseDown$.pipe(
      switchMap(() => timer(500).pipe(takeUntil(mouseUp$)))
    );
    
    stream$.subscribe(() => console.log('Only Fired after 500ms'))
    推荐文章