javascript - Is this really the best way to get a Rx.Observable from an event callback? -


i want stream of events datamaps library since library not written reactive programming in mind i'm having difficult time map emitted event observable. best attempt far this, doesn't feel idiomatic. best can or maybe missing basic rxjs construct make better/simpler/more readable?

import rx 'rx';  import {eventemitter} 'events';  import datamap 'datamaps';    const eventemitter = new eventemitter();  const mapevents$ = rx.observable.fromevent(    eventemitter,    'mapevent'  )  const map = new datamap({    element: document.getelementbyid('map'),    done: (datamap) => {      datamap.svg        .selectall('.datamaps-subunit')        .on('mouseover', (o) => {          eventemitter.emit('mapevent', o);        });    }  });

looks you're using eventemitter event bus, have subjects use instead. subjects both observers , observables, means can call onnext on them give them next event , can use operators on observable sequence.

simply, i'd rewrite this:

import rx 'rx'; import datamap 'datamaps';  const datamapssubject = new rx.subject(); const map = new datamap({   element: document.getelementbyid('map'),   done: (datamap) => {     datamap.svg       .selectall('.datamaps-subunit')       .on('mouseover', (o) => {         datamapssubject.onnext(o);       });   } }); 

if need can construct on subscription , destroy on disposal/unsubscription, might consider observable.create, looks you're targeting 1 div element now.


Comments