Skip to content
Advertisement

How to achieve a maintainable, reactive UI with vanilla JS

today I’ve got a problem which would be easily solved by using a reactive and state managed framework like Vue. Sadly, its not posssible to use it.

Following (simplified) situation (link to codepen): We’ve got a server rendered page which has a price field. It has the opportunity to add or remove a note. If we add a note, its posted to the server and the UI should update itself. Same for removing a note.

JavaScript
JavaScript
JavaScript

To achieve this (only!) javascript is used to update the view. Therefore many classlist.toggle("..") calls or other things are done to display / hide elements. Additionally,there is a bunch of different operations which does also update the view on different places.

To keep the code maintainable I want to achieve, that the UI update is done at one central place and not split across different calls. Also state should be kept for page reload.

Whats an easy and maintable way to do so?

My thoughts: Implement a little state machine (INITIAL, OPEN_NOTE, CLOSED_NOTE, …) and a render()-function which depends on actual state. To keep changes for page reload, localstorage has to be used or server side rendered html needs to stateful aswell.

Advertisement

Answer

I followed my thoughts by implementing internal state with a render-function which holds all UI related changes.

JavaScript

State after page reload is determined from custom attributes of server side rendered html:

JavaScript

Its by far not the best solution, but it helps me to keep things simple.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement