Rxjs,fromEvent处理多个事件 [英] Rxjs, fromEvent to handle multiple events

查看:841
本文介绍了Rxjs,fromEvent处理多个事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is the best way to handle multiple events on the same DOM node in rxjs 5.1?

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

fromEvent($element, 'event_name') but I can specify only one event at a time.

我要处理scroll wheel touchmove touchend个事件.

推荐答案

注意:这是针对RxJS v5的.有关v6版本,请参见此答案的底部.

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

You can use the Rx.Observable.merge function to merge multiple observable streams into a single stream:

// 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对象. 如果您不需要在某些时候分别引用事件及其关联的可观察值,则效果最好:

If that seems a little bloated, we might clean up a little by creating an array for the events, and then map that array to Observable objects. This works best if you do not need to reference the events their associated observables separately at some point:

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

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

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

You are now able to handle all events with one single subscription:

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


更新RxJS v6

在RxJS 6中,您可以导入独立的 merge fromEvent 功能等同于v5中的静态方法,并使用它们同样的方式:

In RxJS 6 you can import the standalone merge and fromEvent functions equivalent to the static methods in v5, and use them the same way:

import { fromEvent, merge } from 'rxjs';

const scrollEvents = fromEvent($element, 'scroll');
// creating other input observables...

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

这篇关于Rxjs,fromEvent处理多个事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆