bryanph bryanph - 2 months ago 19x
Javascript Question

Use RxJS for D3 selection events

I'm trying to get an Observable from a d3 "enter" selection. I can't find a way to do this properly.

For example, for the following selection:

.attr("class", "node")
.attr('id', (d) =>

Where selection is an enter() selection, i want to have the click event as an Observable. How can I do this?

I tried with fromEvent

const clickStream = Rx.Observable.fromEvent(selection[0], 'click')

Which seems like it should work because selection[0] is an array of DOM nodes (right?).

So how can I let this play nice together?


I ended up using part of noppa's suggestion. At the beginning of the enter selection I set an enter-selection flag as a class

.attr("class", "node")
.classed('enter-selection', true) // for rxjs..

Then I select the corresponding enter selection using querySelectorAll:

const domNodes = document.querySelectorAll('.node.enter-selection')

Then I subscribe to the events that i need, for example:

const domNodes = document.querySelectorAll('.node.enter-selection')

And finally at the end of the enter selection I remove the class flag:

selection.classed('enter-selection', false)