Model Binding: HTML Templates
Excerpt by Phil Ledgerwood
MVVM stands for Model-View-ViewModel and describes a client rendering design pattern.
- The Model represents your actual data, such as might be pulled from a database or a service.
- The View is the actual UI that renders the ViewModel, which will generally be HTML in the case of typical web application development.
- The ViewModel is Model data that has been shaped specifically with the goal of binding this to a View that will render the data.
This may not sound all that different from the MVC or MVP patterns, but one of the things that makes the MVVM pattern a little more exciting is that changes to the ViewModel can update the View and the Model immediately.
Let's consider the traditional client-server way of editing data. If you want to add a new customer in a web application:
- Pull up an HTML form and make changes to the form.
- >Click Submit so the page posts this data to code that writes it into the database.
- The page refreshes with any new information such as Customer Id.
Now let's consider using MVVM to edit data. With the MVVM pattern, a ViewModel sits between the View (the form) and the Model (the data from the database), which gives you flexibility on when and how these updates happen >and renders the changes in real-time. If you want to add a new customer using MVVM:
- Fill out the Add Customer form.
- Click Submit, which adds the customer to the ViewModel.
- This change automatically updates an Added Customers grid at the bottom of the page with no refresh.
At this point you can decide if you want the new customer to be saved directlyto the database. If you do, then as soon as your server-side code saves the customer and gets the Id, it can put the Id into the ViewModel which automatically updates any UI elements bound to it.
You could also keep the "Added Customers" in the ViewModel but not save any of them until the user clicks the Commit Changes button. This allows theuser to add, update, or delete all kinds of operations on that data with a UI thatresponds immediately to changes but doesn't commit anything to the database until it's told to.
The main point is that in MVVM, the ViewModel is directly bound to the View, so any changes to it automatically update the View. This adds a huge level of responsiveness and options when writing web applications. Some applications are referred to as Single-Page Applications because the MVVMpattern enables users to do everything on a single page bound to a modifiable ViewModel.
Binding ViewModels to HTML