A recent MSDN forum post asked a good question, one that I realized isn’t often adequately answered for developers new to the concept of data binding. It’s simply then question, “When do I use data binding at all?”
Here’s how I answered the question, and I’d enjoy hearing your thoughts on the matter.
Data binding is typically used to set up an automatic relationship between a data source and one or more UI elements. This is so you can
- Simplify the initialization of UI element contents from a data source (one-time binding)
- Have the UI elements update whenever the data source changes (one-way binding, which effectively includes one-time)
- Have changes in the UI element also be reflected back to the data source (two-data binding, which includes one-way)
When small bits of UI are involved, you can just as easily do all this manually, just by setting innerText/innerHTML values (or other attributes) within the appropriate event handler. However, when the UI gets more involved, e.g. you’re using collections or you’re starting to set up relationships to multiple properties of multiple elements, then having a more formalized structure to handle the data-to-UI wiring starts to make a lot of sense. This is really what data-binding is meant for (and really shines when you’re dealing with database sources and other large data sets.)
“Formalized structure” is what you often see referred to in the context of “view models” (e.g. model-view-controller (MVC), model-view-viewmodel (MVVM), and so forth). Those patterns are ones that have developed from data-binding capabilities; they encapsulate a structure wherein data (the model) is managed independently of how it’s shaped (view), how it’s presented (viewmodel), and how it’s manipulated procedurally (controller). These patterns achieve a ‘separation of concerns’ between data and UI, which is an adjunct to a similar but different separation between markup (HTML), styling (CSS), and code (JS).
[Here I inserted this note as the question was related to WinJS: Note that WinJS provides mechanisms for one-time and one-way data-binding, but not two-way; the latter, however, is not too hard to wire up on your own. I talk about all this in Chapter 4 of my book.]
The bottom line is that data binding is really a best practice, but not a requirement, especially in simple cases.