Reputation: 53840
I have a CRUD app that is mostly rendered as static pages on server side then is enriched with JavaScript on load.
I am looking at Elm examples and see that it generates DOM elements and makes them all dynamic.
I wonder if I can make Elm work on an existing page with a set of DOM elements already there. Is it supposed to work like this at all?
Say, I have an unordered list on the page:
<ul class="items-list">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<ul>
How do I a attach my Elm app to this list and make it a part of the app so that if user interacts with the list, Elm handles the events and model changes?
Upvotes: 3
Views: 200
Reputation: 1073
Elm works best either as a small widget or a monolith. Communicating state between several widgets will get complicated really fast. Ideally, you don't really want to live in a world with both Elm and regular DOM are supposed to interop. The case where it could be okay is like headers/footers/sidebars, list in the content is something you want to try to maintain. You'd be better off sending up JSON for your list and rendering it. If you can't do that, I'd replace the contents with virtual DOM
//: HTMLElement
const itemsList = document.querySelector(".items-list")
//: [String]
const items = Array.from(
itemsList.querySelectorAll("li"),
(li, _) => li.textContent.trim()
)
// Clear list & Mount your app in the list passing the list data in
// as a flag
itemsList.innerHTML = ""
const app = Elm.Main.embed(itemsList, { items })
Now you have a your list data into an Elm widget and can do whatever Elm-y things you wanted. You could maybe consider visually hiding the page and using a complex series of ports to query that DOM as if it was XML data, but I wouldn't recommend that over just Html.send
ing for JSON data. Right now it's best to let the virtual DOM become your application—this isn't jQuery land here.
FWIW, it would seem server-side rendering is slated for Elm next version.
Upvotes: 2