Understanding MVC Services for Front End: TypeScript

A step-by-step TypeScript tutorial

Carlos Caballero
Oct 24, 2019 · 6 min read

Introduction

This post is the second in a series of three posts to understand how the MVC architecture works to create front-end applications.

The objective is to comprehend the way to structure a front-end application by evolving a webpage in which JavaScript is used as a scripting language toward an application in which JavaScript/TypeScript is used as an object-oriented language.

In this second post, the application will be built using TypeScript from the first version. Therefore, this article is where the application will be migrated from VanillaJS to TypeScript. However, it is very important to understand how all the parts of the application are related and how it is structured.

Finally, in the last article, we will transform our code to integrate it with the Angular framework.


Project Architecture

There’s nothing more valuable than an image to understand what we’re going to build. There’s a GIF below in which the application we’re building is illustrated.

Users app

This application can be built using a single TypeScript file which modifies the DOM of the document and performs all operations, but this is a strongly coupled code and is not what we intend to apply in this post.

What is the MVC architecture? MVC is an architecture with three layers/parts:

  • Models — Manage the data of an application. The models will be anemic (they will lack functionalities) since they will be referred to the services.

Below, we show the file structure that we’ll have in our problem domain:

The index.html file will act as a canvas on which the entire application will be dynamically built using the root element. In addition, this file will act as a loader of all the files since they’ll be linked in the HTML file itself.

Finally, our file architecture is composed of the following TypeScript files:

  • user.model.ts — The attributes (the model) of a user

The HTML file is the one shown below:

You can see that only one file called bundle.js has been linked, which will be generated after TypeScript transpilation to JavaScript and applying a minimized task.

We won’t focus on the tools to build our application since we’re going to show the gulpfile file that’s responsible for performing all the transformation tasks of our project.

In this case, we’ve decided to use the Gulp tool since it has years of experience giving extraordinary results. In case you want to go deeper into Gulp, I recommend you look for information on its website since you can find a long list of plugins.

In any case, if you know JavaScript, you’ll be able to read the code, and you’ll almost perfectly understand the tasks we perform. In our example, we have used the browserify plugin to package, create the module system, and perform TypeScript-to-JavaScript transpiling.


Models (Anemic)

The first built class in this example is the application model, user.model.ts, which consists of the class attributes and a private method that is generating random IDs (these IDs could come from a database in the server).

The models will have the following fields:

  • id: Unique value

The User class has been typed using TypeScript. However, the User constructor receives a plain object that’ll be provided from LocalStorage or from the user data input through the form. This plain object must comply with the UserDto interface in such a way that any plain object cannot be instantiated but those that satisfy the defined interface.

The user.model.ts is shown below:


Services

The operations performed on users are carried out in the service. The service is what allows the models to be anemic, since all the logic load is in them.

In this specific case, we’ll use an array to store all users and build the four methods associated with reading, modifying, creating, and deleting (CRUD) users.

You should note that the service makes use of the model, instantiating the objects that are extracted from LocalStorage to the User class. This is because LocalStorage only stores data and not prototypes of stored data. The same happens with the data that travels from the back end to the front end — they do not have their classes instantiated.

The constructor of our class is as follows:

Note: We have defined a class variable called users that stores all users once they have been transformed from a plain object (UserDto) to a prototyped object of the User class.

The next thing we must define in the service will be each of the operations we want to develop. These operations are shown below using TypeScript:

It remains to be defined the commit method that is responsible for storing the operation performed in our data store (in our case LocalStorage).

This method invokes a callback function that’s been binded when creating the zervice, as it can be seen in the definition of the bindUserListChanged method. I can already tell you this callback is the function that comes from the view and is responsible for refreshing the list of users on the screen.

The file user.service.ts is as follows:


Views

The view is the visual representation of the model. Instead of creating HTML content and injecting it (as it’s done in many frameworks), we have decided to dynamically create the whole view.

The first thing that should be done is to cache all the variables of the view through the DOM methods as shown in the view constructor:

The next most relevant point of the view is the union of the view with the service methods (which will be sent through the controller). For example, the bindAddUser method receives a driver function as a parameter that is the one that’ll perform the addUser operation, described in the service.

In the bindXXX methods, the EventListener of each of the view controls are being defined. Note that from the view, we have access to all the data provided by the user from the screen, which are connected through the handler functions.

The rest of the code of the view goes through handling the DOM of the document. The file user.view.ts is as follows:


Controllers

The last file of this architecture is the controller. The controller receives the two dependencies it has (service and view) by dependency injection (DI).

Those dependencies are stored in the controller in private variables. In addition, the constructor makes the explicit connection between view and services since the controller is the only element that has access to both parties.

The file user.controller.ts is the one shown below:


App.ts

The last point of our application is the application launcher. In our case, we’ve called it app.ts.

The application is executed through the creation of the different elements: UserService, UserView, and UserController, as shown in the file app.ts.


Conclusions

In this second post, we have developed a web application in which the project has been structured following the MVC architecture in which anemic models are used and the responsibility for the logic lies on the services.

It’s very important to understand the structuring of the project in different files with different responsibilities and how the view is totally independent of the model/service and the controller.

It’s also important to note that in this post, we have migrated the application from JavaScript to TypeScript, allowing us to obtain a typed code that helps the developer minimize errors and understand what each part of it does.

In the next post of this series, we will migrate the TypeScript code to Angular. This migration to a framework will mean we don’t have to deal with the complexity and repetitiveness of working with the DOM.

The GitHub branch of this post is located here.

Better Programming

Advice for programmers.

Thanks to Zack Shapiro

Carlos Caballero

Written by

Hi! My name is Carlos Caballero and I’m PhD. in Computer Science from Málaga, Spain. Teaching developers and degree/master computer science how to be experts!

Better Programming

Advice for programmers.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade