This important tip is “Watch Data not DOM”. It will always be good to keep data as a single source of truth and make the DOM a reflection of it. This is what all major libraries are doing as well.
Obviously you will need to implement the supplementary data structure to support the program but that will be worth it.
Consider this example:
Now this example will run add function everything something is checked or unchecked. and in case large number of checkboxes; it will be slow and won’t generate correct results in case of large data as program will have to go through each and every DOM element to identify the data and make sure what to do with it.
We can redo this example as following:
The above code has one event handler and has track of everything through data.
Lookup in data is easy rather than in DOM.
Moreover when you are making sure that DOM is in sync with Data, events are also easy to handle. Like in above example, all the events are delegated to the container and event itself has all the necessary information about the actions.
event.target is the reference to the element which has be acted itself, it is does not require another query to DOM again. Event handlers are also reduced from being equal to the number of checkboxes in the app to just one handler.
So before approaching the problems of UI, just sit back and think about the data. Once the necessary transitions are clear, you can go ahead and write the code in a very declarative and functional manner; rather pure functions.
Subscribe to Time to Hack
Get the latest posts delivered right to your inbox