Chapter 6. Controllers and View Models

Up until this point, the controllers we wrote for our application have been extremely basic. They were started with a simple task of sending text responses to the client. In the previous chapter, we updated the controllers so that they render an HTML view and send the HTML code to the client, instead of a simple text response. The primary job of a controller is to act as the entity, which holds the logic that makes all of the necessary decisions to properly render a response to the client. In our case, this means retrieving and/or generating the data necessary for a page to appear complete.

In this chapter, we will:

  • Modify the controllers so that they generate a data model and pass it to a view
  • Include logic to support uploading and saving image files
  • Update the controllers to actually render dynamic HTML
  • Include helpers for the partials that generate the website statistics
  • Iterate on the UI to include improved usability via jQuery

Controllers

A controller can be defined as the entity that will be responsible for manipulating models and initiating the view render process with the data received from the corresponding models. In the code we have developed so far, we can see that the express router instance is used to tie functions to a corresponding route. These functions are nothing but controllers. For every route that we create in our router, two parameters are necessary:

  • The first parameter is the string for the route itself, which is /images/:image_id
  • The second parameter is a controller function that will be executed when that route is accessed

For any route that has to do with images, we rely on the images controller. Likewise, any route that has to do with the home page relies on the home controller, and so on and so forth.

The steps we will take to define our controllers in our app are purely organizational and based on personal preference. We created our controllers as modules so that our router wasn't a big, long convoluted mess of spaghetti code. We could have just as easily kept all of the logic contained in our controllers as functions directly within the routes themselves, but this would have been an organizational mess and made for very hard-to-read code to maintain later.

As our sample app is fairly small, we only have two controllers currently: home and image. It is the responsibility of these controllers to build the appropriate view models for our HTML pages and render the actual pages as well. Any logic that is required to execute per page and build the view model will be done so via our controllers.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.225.55.151