Hacker News new | ask | show | jobs
by citeguised 2582 days ago
When I got into front-end coming from Design, jQuery just got huge. Due to lack of senior front-end-devs in the company, my JS was this exact pile of jQuery with state in data-attributes. The things weren't really complex (Modals, Tabs, Form-Validation etc.), so it was never a problem.

Nowadays I'd still do simpler components this way. For anything heavier I'll grab React from the beginning, because of it's enforcement of modularity and state-management.

I'm interested in the way of architecting things you described, since I used to try similar ways, but always ended up state-in-dom. Would you have examples or literature on this?

2 comments

I started out much the same way, and took that approach for quite a while.

These days I avoid putting state in my markup even for small stuff. I remember some good articles on the topic, but sadly can't find them.

But at its most basic, I just make sure that any jQuery/dynamic component/widget, from the start, is essentially a render function that takes a bunch of data and updates the markup with this data (triggered via some event handler or setInterval(), or something like that). In many cases this doesn't have to be complex or efficient. Sometimes just an .innerHTML() or whatnot is fine. The crucial bit is that I always start with a js data structure and treat it as the single source of truth.

In most cases I just use Preact from the beginning, but I've worked on projects where that wasn't possible and I had to use jQuery or plain javascript. Whatever I used, I usually ended up regretting state in my markup.

If you know you will need the data again store it in some variable, in addition to the dom?

For instance if you have a chat, you could have a list of message objects as a normal variable and also show those messages in the dom.