Front End Tip: Watch Data not DOM

Watch Data not DOM

Watch Data not DOM

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.

This post is from the answer I wrote on Quora which can be read here:

Obviously you will need to implement the supplementary data structure to support the program but that will be worth it.

In JavaScript, Reading and Writing/Updating the DOM are costly things, and it has side effects and quirks of its own.

Consider this example:

See the Pen t2h-tip1-ex2 by Pankaj Patel (@pankajpatel) on CodePen.

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:

See the Pen t2h-tip1-ex1 by Pankaj Patel (@pankajpatel) on CodePen.

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. `` 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.

Got Something To Say:

Your email address will not be published. Required fields are marked *