在 rxjs 5.1 中处理同一个 DOM 节点上的多个事件的最佳方法是什么?
fromEvent($element, 'event_name')
但我一次只能指定一个事件。
我想处理scroll wheel touchmove touchend
事件。
注意:这适用于 RxJS v5。有关 v6 和 v7 的等效版本,请参阅此答案的底部。
您可以使用该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 对象。如果您不需要在某些时候单独引用事件与它们相关的 observables,这种方法效果最好:
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 和 v7 的更新
从 RxJS 6 开始,您可以导入与v5 中的静态方法等效的独立merge
和函数,并以相同的方式使用它们:fromEvent
import { fromEvent, merge } from 'rxjs';
const scrollEvents = fromEvent($element, 'scroll');
// creating other input observables...
const allEvents$ = merge(
scrollEvents$,
wheelEvents$,
touchMoveEvents$,
touchEndEvents$
);
这就是我在最新版本的 RxJs 中实现它的方式
const events = ['scroll', 'resize', 'orientationchange']
from(events)
.pipe(
mergeMap(event => fromEvent($element, event))
)
.subscribe(
event => // Do something with the event here
)
这就是我更喜欢组合事件的方式:
fromEvents(dom, "scroll", "wheel", "touch", "etc...");
function fromEvents(dom, ...eventNames: string[]) {
return eventNames.reduce(
(prev, name) => Rx.merge(prev, fromEvent(dom, name)),
Rx.empty()
);
}
如上所述,希望下面更容易阅读。
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
)