Rxjs,fromEvent来处理多个事件

时间:2017-08-03 21:58:07

标签: angular rxjs5 rxjs-dom

在rxjs 5.1中处理同一DOM节点上的多个事件的最佳方法是什么?

fromEvent($element, 'event_name')但我一次只能指定一个事件。

我想要处理scroll wheel touchmove touchend个事件。

4 个答案:

答案 0 :(得分:29)

注意:这适用于RxJS v5。有关v6等效内容,请参阅本答案的底部。

您可以使用Rx.Observable.merge函数将多个可观察流合并为一个流:

// First, create a separate observable for each event:
const scrollEvents$    = Observable.fromEvent($element, 'scroll');
const wheelEvents$     = Observable.fromEvent($element, 'wheel');
const touchMoveEvents$ = Observable.fromEvent($element, 'touchmove');
const touchEndEvents$  = Observable.fromEvent($element, 'touchend');

// Then, merge all observables into one single stream:
const allEvents$ = Observable.merge(
    scrollEvents$,
    wheelEvents$,
    touchMoveEvents$,
    touchEndEvents$
);

如果这看起来有点臃肿,我们可能会通过为事件创建一个数组来清理一下,然后将该数组映射到Observable对象。这最好如果你不需要在某些时候单独引用它们相关的可观察事件:

const events = [
    'scroll',
    'wheel',
    'touchmove',
    'touchend',
];

const eventStreams = events.map((ev) => Observable.fromEvent($element, ev));
const allEvents$ = Observable.merge(...eventStreams);

您现在可以使用一个订阅来处理所有事件:

const subscription = allEvents$.subscribe((event) => {
    // do something with event...
    // event may be of any type present in the events array.
});

更新RxJS v6

在RxJS 6中,您可以导入standalone merge function与v5中的静态方法等效,并以相同的方式使用它:

import { merge } from 'rxjs';

// creating the input observables again...

const allEvents$ = merge(
    scrollEvents$,
    wheelEvents$,
    touchMoveEvents$,
    touchEndEvents$
);

答案 1 :(得分:2)

这是我更喜欢组合事件的方式:

fromEvents(dom, "scroll", "wheel", "touch", "etc...");
function fromEvents(dom, ...eventNames: string[]) {
    return eventNames.reduce(
        (prev, name) => Rx.merge(prev, fromEvent(dom, name)),
        Rx.empty()
    );
}

答案 2 :(得分:2)

这就是我将在最新版本的RxJs中实现的方法

const events = ['scroll', 'resize', 'orientationchange']
from(events)
  .pipe(
    mergeMap(event => fromEvent($element, event))
  )
  .subscribe(
    event => // Do something with the event here
  )

答案 3 :(得分:0)

如上所述,希望以下内容易于阅读。

        import {fromEvent, merge} from "rxjs";
        
        
        const mousemoveEvent = fromEvent(document, 'mousemove');
        const wheelEvent = fromEvent(document, 'wheel');
        const leftclickEvent = fromEvent(document, 'auxclick');
        const rightclickEvent = fromEvent(document, 'click');
        const keyboardEvent = fromEvent(document, 'keydown');

        const allEvents = merge(
            mousemoveEvent, wheelEvent, leftclickEvent, rightclickEvent, keyboardEvent
        )