What makes custom elements different from other non-port approaches to JS interop?

Instead of being shunned and considered a hack, custom elements are universally embraced. I’m curious what sets them apart from other approaches that let you use JS in elm without ports. (so far I’ve just stuck to ports and haven’t tried the custom element approach, just briefly looked at some code that used it.)

you can’t share references between elm and web-component. To name at least one.

1 Like

A web component should act as any other dom node and should act with just attributes and properties passed in, and events passed out. That flow matches a lot of the Elm pattern of message passing. Also, Elm is for building things on the dom and web components are a relatively genericized part of the dom.

This is just my guess.

1 Like

I don’t think they are embraced anymore than ports, and like ports, they are not allowed in packages (at least the javascript part, the rest being standard elm/html) and they are a last resort option when things cannot be done yet in pure Elm.

There are a few elements of response there:
https://guide.elm-lang.org/interop/limits.html.

Given these pitfalls, ports and custom elements are attractive because they let you get things done in JavaScript while preserving the best parts of Elm.

Compared to kernel code, of the top of my head, I would say:

  • They do not allow to make synchronous functions that could mutate data and therefore break functional purity.
  • They can only be used in HTML views. This prevents them being used for things that are better done in pure Elm to stay portable (data structures algorithms, parsing, encoding, …).
  • They usually only act on their own DOM sub-tree and javascript object and have therefore usually no side effect on the Elm code part (there are exceptions, like in ports, and those can break your application, that’s why they are not allowed in packages).
  • Their API from Elm is well defined, already used in elm/html, and does not require some specific maintenance (DOM nodes attributes, properties and events).
3 Likes

To my understanding, custom elements are the best way to bring external UI into Elm.

Elm’s virtual DOM will get confused if a JS library changes DOM nodes. So, the best way to use a complex UI implemented in JS is to encapsulate it in a web component and have Elm treat the entire UI as if it was a regular dom node.

So, like the Pie Chart example shows, you can bring something like the Google Charts UI into Elm and treat it just like a regular Html element.

3 Likes

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