在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 开始,您可以导入独立的 merge
和 fromEvent
函数,它们与 v5 中的静态方法相等,并且可以以相同的方式使用:
import { fromEvent, merge } from 'rxjs';
const scrollEvents = fromEvent($element, 'scroll');
// creating other input observables...
const allEvents$ = merge(
scrollEvents$,
wheelEvents$,
touchMoveEvents$,
touchEndEvents$
);
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
)