Simple data reactivity for DOM elements with Data Live
Reactivity is a big topic in frontend development with all the big JavaScript frameworks using it in some form to keep data and UI in sync. But do you really need to use a whole framework? I recently had two projects, a calculator and a countdown timer which needed reactivity so I decided to explore a simpler solution.
The simplest solution I found was Unravel Reactivity in 16 lines of Vanilla JS by Michele Rullo. This approach relied on adding a data attribute to an element which corresponded to a piece of data. When the data was updated the text in the element was updated, which is exactly what I needed.
I thought that I could take this idea and make it more flexible to handle more complex data. I remembered reading about Proxies on the excellent Go make things blog which led me to Simple reactive data stores with vanilla JavaScript and Proxies, A primer on JavaScript Proxies and Reef JS by Chris Ferdinandi.
These inspired the creation of Data Live, my own utility library for reactive DOM elements. My approach is to use a Proxy as a data store, which emits a Custom Event as a signal that that data has changed. The signal causes the effect i.e. updating text, on the DOM elements which can be a template for complex presentation.
For text based updates just add the script and add data-live="text" attribute to an element. Update the data e.g. window['text']['text'] = 'New text value' and the elements text will update. For complex data you can set up a component which includes a template for data presentation e.g. let usersComponent = component(dataArray, 'users', usersTemplate);.
This is not a replacement for frameworks or other reactivity libraries but more of a useful utility to add to your own project. See Data Live for full documentation and demos.