sprotty icon indicating copy to clipboard operation
sprotty copied to clipboard

How to addEventListener to svg nodes?

Open com-nvidia-yohuang opened this issue 4 years ago • 4 comments

I realize that the svg elements are available only after rendering. I tried to addEventListener in the final block like below. But the allSvgNodes is empty array.

Maybe I should get the element from mouseEvent, and addEventListener for the element then?

thanks.

elk.layout(graph)
   .then(g => {
       var sGraph = new elkgraph_to_sprotty_1.ElkGraphJsonToSprotty().transform(g);
       modelSource.setModel(sGraph)
   })
   .catch(function (e) {
       console.log(e);
   })
   .finally(() => {
      var allSvgNodes = [...document.getElementById('sprotty').querySelectorAll("*")]
      ... code to add listener
      })

com-nvidia-yohuang avatar Jan 14 '21 14:01 com-nvidia-yohuang

The actual rendering of SVG elements happens asynchronously. I'm not sure, but you could try

return modelSource.setModel(sGraph);

and change the finally block to another chained then.

spoenemann avatar Jan 14 '21 15:01 spoenemann

Hi Spoenemann,

allSvgNodes now has one element [svg#sprotty_EMPTY] after making the changes as you suggested.

thanks.

com-nvidia-yohuang avatar Jan 15 '21 05:01 com-nvidia-yohuang

Ok so the following DOM updates are not captured by the promise returned by setModel.

We could consider adding a listener mechanism to the Viewer component. In the meantime, you could try registering a IVNodePostprocessor, which is notified after a rendering update. See examples here:

https://github.com/eclipse/sprotty/blob/ae671b54aa48f991ca036906bd04ac0ad309ab9f/src/base/di.config.ts#L132-L147

spoenemann avatar Jan 15 '21 08:01 spoenemann

I extended MouseListener to print the element clicked in doubleClick handler, and I can see the right node element printed. I can get the Node information from the (target, event) parent of the handler.

Thanks a lot!

I am experimenting other potential choices to see if we can decouple the event listener from sprotty code to make the sprotty related code more reusable in different similar applications.

com-nvidia-yohuang avatar Jan 15 '21 13:01 com-nvidia-yohuang