Node.js | Controllers and View Models


A controller renders a response to the client. It generates the data necessary for a page to appear complete.

A controller manipulates models and initiates the view render process with the data received from the
corresponding models. A controller is a function. A controller function is executed when its corresponding route is accessed.

In the case of the Project1 (on this website), for any route that has to do with images, we rely on the images controller. Any route that has to do with the home page relies on the home controller, and so on
and so forth. We created our controllers as modules so that our router wasn’t a big, long piece of code.

Our Project1 has two controllers: home and image. They build the appropriate view models for our HTML pages and render the actual pages as well.

View models

A view model is typically just a single JavaScript object that can be passed to the template. The template contains all of the necessary logic we need to properly render the page. It is the task of the templating engine to produce the corresponding HTML by processing the templates with the associated models.

The view model for a page will typically contain all of the data necessary to render the content-specific portions of that page. In our case, the view model for a specific image’s page might contain the title of the image, its description, and the information necessary to display the image and various stats such as the number of likes, views, and a collection of comments.

Leave a Reply