Model of a Modern View Design Pattern

(“I am the very” made the title two lines, sorry W.S. Gilbert)

For ~reasons~, I have been teaching myself a bit of Angular 1 lately. In doing so, I re-encountered the Model-View-ViewModel design pattern. I remembered hearing about this back when I first learned the Model-View-Controller pattern, and I wanted to clarify for myself (and you, my hypothetical readers) the differences between them.

Turns out these two patterns are not mutually exclusive. Angular has both ng-controllers and view-models/$scope, and they work together. Model and View are concepts common to both of these patterns. (Sometimes you’ll hear about MV*, where the asterisk is a wildcard for controller, view-model, presenter, or whatever.)

image via a very useful StackOverflow thread

The Model is a representation of the data itself. Sometimes it’s the result of an API call, sometimes its an object representation of info from your database. It knows about itself, but does not know how to show itself to your audience. In this scenario, it’s a Javascript file.

The View, on the other hand, is literally what your audience sees. It knows how you want the data formatted. It’ll usually be a HTML/CSS file. But it doesn’t know what that data is, without some other layer allowing it to communicate with the model.

A Controller is one way to coordinate that communication. It would also be a Javascript file. Every action in taken in an MVC view, from rendering the homepage to sending through a form, is routed through the controller. The controller takes the url parameters or form data, asks the model for the relevant data, then sends back the next view.

A ViewModel is kind of a more direct way to communicate. In Angular, it isn’t really a separate file of it’s own but rather a component of the native API ($scope). Basically, it knows the shape of the data and exposes methods to manipulate that data for viewing purposes. This is more reactive than a controller, because it is always listening for changes in the observables rather than only activating when an HTTP request is sent.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.