在rxjs 5.1中处理同一DOM节点上的多个事件的最佳方法是什么?
fromEvent($element,’event_name’)但我一次只能指定一个事件.
我想要手柄滚轮touchmove touchend事件.
您可以使用
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. });