Model-View-Viewmodel
MVVM, Model-View-Binder
- Definition
- A UI pattern that adds an abstract representation of the view outside of the view: the viewmodel. The state of the view is automatically synchronized with the viewmodel by a binder. The binder is provided by a framework. The viewmodel also serves as adapter, preparing data for the view and the model.
The view is the visual representation of the component that allows the user to interact with the application.
The viewmodel has two functions: it keeps the state of the view, outside of the view. Basically it contains the values of the ui components. It also serves as an adapter, preparing data for the view and for the model.
The binder syncs the state of the view to the viewmodel and vice-versa.
The model contains domain logic available on the client and connects to external domain (e.g. database)
How does it work?
Modern frontend frameworks have a hierarchical component structure where each component is self-contained. The view is as compact and close to the resulting output (i.e. HTML) as possible. The view declares any handler functions needed that are activated when events occur. The viewmodel contains both a data structure and adapter logic. The state of the view is automatically synced to the viewmodel data structure by the binder that is part of the framework. The viewmodel also serves as adapter and prepares data for the view and the model. Each component has a lifecycle that consists of hooks that are executed when the component is created, mounted, unmounted, etc. Since these are often client-server applications, part of the domain is available in the client, and part of it on the server.
Examples
- Vue
- React
Where does it come from?
It was invented by Microsoft architects Ken Cooper and Ted Peters specifically to simplify event-driven programming of user interfaces.
When should you use it?
MVVM works very well when building a complex Single Page Application.
Problems
The "magic" of the viewmodel must be well-understood and designed. If not, a simple change in the input can lead to an avalanche of automatic effects, that can slow the application down.