Data binding for Web Components in just a few lines of code
It’s not rocket science and Virtual DOM is usually overkill anyway.
Earlier this year I wrote an article in which I claimed that Web Components will eventually replace frontend frameworks.
It generated quite some response, more than I could have hoped for and it gave me some interesting opportunities. Lots of people agreed with me, others were more critical and a few people thought I was completely out of my mind and should be banned from writing code forever. In general, good points were being made on both sides.
The main criticism was that the existing frameworks enable a declarative way of writing views through data binding, which is something native Web Components do not provide out of the box. This in itself is a valid point, but nevertheless data binding is easy to achieve for Web Components as I will demonstrate in this article.
The case for declarative data binding
Data binding was first made popular by frameworks like Angular, Backbone and Ember and is now more or less the de facto way of writing views. It enables the “view as a function of data” which means that whenever some data changes, the associated view will “automatically” update.
No more verbose DOM manipulation to keep data and view in sync, just update the data and the view will follow. A killer feature that no sane developer wants to do without these days. It’s easy to understand why developers choose to use a framework that provides data binding, even for apps for which a framework is clearly overkill. Why go through the hassle of verbose DOM manipulation when a framework provides it out of the box?
But data binding is not magic and you don’t need a whole framework to use it. It is easy, trivial even to implement with Web Components in just a few lines of code.
How it works
Like I said, data binding is not magic. Your view does not “magically” update when the underlying data changes. Somewhere, buried deep down in that framework code are setters that get invoked when the data changes and that take care of updating the view.