Rxjs, fromEvent to handle multiple events

Viewed 23408

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

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

I want handle scroll wheel touchmove touchend events.

4 Answers

This is how I would implement this in the newest version of RxJs

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

This is how I prefer to combine events:

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

As mentioned above, Below hopefully is easier to read.

        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
        )
        
        

Related