Building a Simple MVC Project from Scratch with JavaScript
I want to introduce the Model View Controller (MVC) architecture through a simple app. At first, MVC can seem abstract and difficult to grasp, but a practical example can make it easier to learn. Follow along and we'll build a small project from scratch using JavaScript.
We'll use the GitHub API to look up a profile and some of its data 😜
First, a quick introduction to MVC:
- The Model handles data. Here, it will request and process data from the GitHub API.
- The View is what you want to display on screen, including the elements tied directly to that presentation.
- The Controller connects the Model and the View. It coordinates which data moves between them.
Now that we have the basics, let's get to work 🔨
We'll start with an HTML structure like this:
<body> <header> GitHub App - Model View Controller (MVC) </header> <main class="container"> <section class="profile"> </section> <form class="filter"> <input type="text" value="" /> <button type="submit">Buscar</button> </form> <section class="repo"> <h2>Repositórios favoritos</h2> <div class="repo-list"></div> </section> </main> <script type="module" src="js/index.js"></script> </body>
You may be wondering why some sections are empty or why the HTML elements already have classes. We'll use those classes to find the elements in our View.
Create a folder called js at the project root with this structure:
The folder will contain the views and models, plus an index.js file that will be our Controller.
Let's start with the Views. We'll create three files.
First, create base.js with shared functions and references to the elements we need to update. The elements object will hold the HTML classes so we can add or remove things from the page 🎨
It will look like this:
export const elements = { profile: document.querySelector(".profile"), input: document.querySelector("input"), repos: document.querySelector(".repo-list"), };
Next, create userView.js inside the views folder. It will contain a renderUser function that builds the HTML after it receives the GitHub user's data:
import { elements } from "./base.js"; export const renderUser = ({ avatar_url, html_url, public_repos, followers, following, }) => { const markup = ` <div class="profile-header"> <img src="${avatar_url}" alt="Avatar"> <a href="${html_url}" target="_blank">Visitar perfil</a> </div> <ul class="profile-list"> <li>Repositórios: ${public_repos}</li> <li>Seguidores: ${followers}</li> <li>Seguindo: ${following}</li> </ul> `; elements.profile.insertAdjacentHTML("afterbegin", markup); };
The renderUser function uses the elements object to reference the profile class. It then inserts the markup into the profile section we defined in the HTML, using insertAdjacentHTML. The first argument sets the position; the second is the HTML to insert.
Now let's create the Model for the user View. Inside the models folder, create User.js. It will contain a User class that requests data from the GitHub API and makes the fields we need available to the View.
class User { constructor(user) { this.user = user; } async getUser() { try { const apiUrl = `https://api.github.com/users/${this.user}`; const apiUrlStarred = `https://api.github.com/users/${this.user}/starred`; const response = await fetch(apiUrl); const result = await response.json(); this.avatar_url = result.avatar_url; this.followers = result.followers; this.following = result.following; this.public_repos = result.public_repos; this.html_url = result.html_url; this.starred_url = apiUrlStarred; } catch (error) { console.log(error); } } } export { User };
The User View and Model are ready. Next is the Repo, which will handle the GitHub repositories we want to display.
Let's begin with the repo View. In views, create repoView.js:
import { elements } from "./base.js"; export const renderRepositories = (repositories) => { let markup = ""; repositories.forEach(({ html_url, name }) => { markup += ` <a href="${html_url}" class="repo-url" target="_blank"> ${name} </a> `; }); elements.repos.innerHTML = markup; };
As with userView.js, this function receives a list of repositories and builds the markup to display them.
For the repository Model, create Repo.js inside models:
class Repo { constructor(repoUrl) { this.repoUrl = repoUrl; } async getRepositories() { try { const response = await fetch(this.repoUrl); this.repos = await response.json(); } catch (error) { console.log(error); } } } export { Repo };
The Repo class receives a URL that returns the repositories for the user we're looking up.
We're nearly done. One file remains—and it's an important one 🥁
That's right: the Controller 🎮
Remember index.js at the root of the js folder? Open it. We'll create two controller functions: one to get user data from the User Model and render the User View, and another to get repositories from the Repo Model and send them to the Repo View.
This makes the Controller's role as the link between Model and View clear.
import { User } from "./models/User.js"; import { Repo } from "./models/Repo.js"; import * as userView from "./views/userView.js"; import * as repoView from "./views/repoView.js"; import { clearUI, elements } from "./views/base.js"; const state = {}; const controlFavoriteRepositories = async (url) => { try { state.repositories = new Repo(url); await state.repositories.getRepositories(); repoView.renderRepositories(state.repositories.repos); } catch (error) { console.log(error); } }; const controlSearch = async (event) => { event.preventDefault(); try { const searched = elements.input.value; state.user = new User(searched); await state.user.getUser(); clearUI(); userView.renderUser(state.user); await controlFavoriteRepositories(state.user.starred_url); elements.input.value = ""; } catch (error) { console.log(error); } }; window.addEventListener("submit", controlSearch); window.addEventListener("load", controlSearch);
The controlSearch function takes the username entered in the input and sends it to the User Model. Once the user data is available, it is stored in a global state object so we can reuse requested values later.
Next, we call getUser() to retrieve the data, then clearUI() (which we'll create in base.js) to remove the existing HTML before rendering the searched profile. We then call controlFavoriteRepositories with the URL we received so it can render the user's starred repositories.
The repository controller follows the same pattern: instantiate the Repo class, get the data, and pass it to the View to display the starred repositories.
A couple of final details: at the bottom of index.js there are two event listeners, submit and load. The submit event runs when a username is searched; load renders the default input value from the HTML. Both call controlSearch.
I set my username as the input's default value, but feel free to use your own GitHub username:
<input type="text" value="IsabelRubim" />
I also created a css folder at the project root and a styles.css file for styles. You can copy them here. Then include the stylesheet in the HTML's head:
<link rel="stylesheet" href="css/styles.css" />
Finally, include the Controller inside the HTML body:
<script type="module" src="js/index.js"></script>
That's it: a simple app that looks up any GitHub user without using libraries and demonstrates the Model View Controller architecture. Here are the live demo and source code:
I hope this tutorial helped you understand MVC. It's a pattern often used in real-world projects and can be useful to know.
