Embedding Elm in python/jupyter notebook

Hello,

I’m new to Elm and currently trying to learn the basics. I’ve walked through the Elm guide and am currently experimenting with ports. To get a feeling for Elm and ports I currently try to embed an Elm app into a Jupyter notebook and to “somehow” expose the app model to python.

To be more specific, I’m trying to just embed the simple “up-down counter” example from the Elm-guide in such a way, that the counter value can be set and read from python and - at the same time - changed with the buttons up and down.

You can try my current version on binder (Execute the cells with SHIFT+ENTER one cell at a time, starting from the first) or clone the repository from GitHub (andrebell/PythonJsElm)

This version, however, isn’t satisfying. I want the counter state to be owned by Elm. Therefore I would like to have python call javascript and that javascript to access the Elm ports to set or read the counter value.

Setting the value is achieved with the javascript call:

app.ports.portSetValue.send(somevalue);

which directly maps to the port

port portSetValue : (D.Value -> msg) -> Sub msg

in the Elm code. That works quite fine and allows to write the python code

c.count = 5

to update the Elm model.

The more difficult part is reading the current counter value. Since the port is asynchronously I can request a new value and subscribe with a callback for the value. However, in this case I cannot return the value synchronously with the read attempt. Therefore, I have to hold a shadow copy of the counter value in python to synchronously return the value at any time.

I have two questions here:

  1. Is it possible to have ports which do not have parameters?
  2. Is it possible to have some means of synchronously return a value from Elm into javascript?

I hope I could explain my attempt. Maybe there is some completely different option I’m missing right now. I would greatly appreciate any comments or advise.

Thanks a lot

Andre

In the case of the up down counter, the value of the counter is rendered by the view. So if you rendered it to an element with a known id you could grab it out of the DOM with javascript. More generally you could render an empty div of known id with any Model values you wanted (or even a JSON encoding of the entire model) by ‘hiding’ them in a data-* attribute.

Perhaps not a very elegant solution though!

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.