The Model View Controller Pattern - MVC Architecture and Frameworks Explained

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

Search 10,900+ tutorials Forum Donate

Learn to code — free 3,000-hour curriculum

APRIL 19, 2021 / #DESIGN PATTERNS

The Model View Controller Pattern – MVC


Architecture and Frameworks Explained
Rafael D. Hernandez
Search 10,900+ tutorials Forum Donate

Learn to code — free 3,000-hour curriculum


Search 10,900+ tutorials Forum Donate

Learn to code — free 3,000-hour curriculum


The MVC
Search architecture
10,900+ tutorials pattern turns complex Forum
ADVERTISEMENT Donate

application development into Learnatomuch more


code — free 3,000-hour curriculum

manageable process. It allows several developers to


simultaneously work on the application.

When I first learned about MVC patterns, I was intimidated by all


the jargon. And even more so when I started applying these
concepts to an actual application.

By taking a step back to focus on what MVC is and what it can


accomplish, it's much easier to understand and apply the pattern
to any web application.

What is MVC?
MVC stands for model-view-controller. Here's what each of those
components mean:

Model: The backend that contains all the data logic


View:10,900+
Search The frontend
tutorials or graphical user interface (GUI) Forum Donate

Learn to code that


Controller: The brains of the application — freecontrols
3,000-hour curriculum

how data is displayed


Search 10,900+ tutorials Forum Donate
The concept of MVCs was first introduced by—Trygve
Learn to code Reenskaug,
free 3,000-hour curriculum
who proposed it as a way to develop desktop application GUIs.

Today the MVC pattern is used for modern web applications


because it allows the application to be scalable, maintainable, and
easy to expand.

Why Should You Use MVC?


Three words: separation of concerns, or SoC for short.

The MVC pattern helps you break up the frontend and backend
code into separate components. This way, it's much easier to
manage and make changes to either side without them
interfering with each other.

But this is easier said than done, especially when several


developers need to update, modify, or debug a full-blown
application simultaneously.
Search 10,900+ tutorials Forum Donate
How to Use MVC Learn to code — free 3,000-hour curriculum
To better illustrate the MVC pattern, I've included a web
application that shows how these concepts all work.

My Car Clicker application is a variation of a well-known Cat


Clicker app.
ADVERTISEMENT

Here are some of the major differences in my app:

1. No cats, only muscle cars images (sorry cat lovers!)

2. Multiple car models are listed

3. There are multiple click counters

4. It only displays the selected car


Search 10,900+ tutorials Forum Donate

Learn to code — free 3,000-hour curriculum

Now let's dive into these three components that make up the
MVC architecture pattern.

Model (data)
The model's job is to simply manage the data. Whether the data is
from a database, API, or a JSON object, the model is responsible
for managing it.
Search 10,900+ tutorials Forum Donate
In the Car Clicker application, the model object contains an array
Learn to code — free 3,000-hour curriculum
of car objects with all the information (data) needed for the app.

It also manages the current car being displayed with a variable


that's initially set to null .


const model = {
currentCar: null,
cars: [
{
clickCount: 0,
name: 'Coupe Maserati',
imgSrc: 'img/black-convertible-coupe.jpg',
},
{
clickCount: 0,
name: 'Camaro SS 1LE',
imgSrc: 'img/chevrolet-camaro.jpg',
},
{
clickCount: 0,
name: 'Dodger Charger 1970',
imgSrc: 'img/dodge-charger.jpg',
},
{
clickCount: 0,
name: 'Ford Mustang 1966',
imgSrc: 'img/ford-mustang.jpg',
Search 10,900+ tutorials  Forum Donate
},
{
Learn to code — free 3,000-hour curriculum
clickCount: 0,
name: '190 SL Roadster 1962',
imgSrc: 'img/mercedes-benz.jpg',
},
],
};

Views (UI)
The view's job is to decide what the user will see on their screen,
and how.

The Car Clicker app has two views: carListView and CarView .

Both views have two critical functions that define what each view
wants to initialize and render.

These functions are where the app decides what the user will see
and how.

carListView
Search 10,900+ tutorials Forum Donate

const carListView = {
init() {
Learn to code — free 3,000-hour curriculum
// store the DOM element for easy access later
this.carListElem = document.getElementById('car-list');

// render this view (update the DOM elements with the right values)
this.render();
},

render() {
let car;
let elem;
let i;
// get the cars to be render from the controller
const cars = controller.getCars(); ADVERTISEMENT

// to make sure the list is empty before rendering


this.carListElem.innerHTML = '';

// loop over the cars array


for(let i = 0; i < cars.length; i++) {
// this is the car we've currently looping over
car = cars[i];

// make a new car list item and set its text


elem = document.createElement('li');
elem.className = 'list-group-item d-flex justify-content-between
elem.style.cursor = 'pointer';
elem.textContent = car.name;
elem.addEventListener(
'click',
(function(carCopy) {
return function() {
Search 10,900+ tutorials  Forum Donate
controller.setCurrentCar(carCopy);
carView.render();
Learn to code — free 3,000-hour curriculum
};
})(car)
);
// finally, add the element to the list
this.carListElem.appendChild(elem);
}
},
};

CarView

const carView = {
init() {
// store pointers to the DOM elements for easy access later
this.carElem = document.getElementById('car');
this.carNameElem = document.getElementById('car-name');
this.carImageElem = document.getElementById('car-img');
this.countElem = document.getElementById('car-count');
this.elCount = document.getElementById('elCount');

// on click, increment the current car's counter


this.carImageElem.addEventListener('click', this.handleClick);

// render this view (update the DOM elements with the right values)
this.render();
},
Search 10,900+ tutorials  Forum Donate
handleClick() {
Learn to code — free 3,000-hour curriculum
return controller.incrementCounter();
},

render() {
// update the DOM elements with values from the current car
const currentCar = controller.getCurrentCar();
this.countElem.textContent = currentCar.clickCount;
this.carNameElem.textContent = currentCar.name;
this.carImageElem.src = currentCar.imgSrc;
this.carImageElem.style.cursor = 'pointer';
},
};

Controller (Brain)
The controller's responsibility is to pull, modify, and provide data
to the user. Essentially, the controller is the link between the view
and model.

Through getter and setter functions, the controller pulls data


from the model and initializes the views.


If there
Searchare any updates
10,900+ tutorials from the views, it modifies the data with Forum Donate
a setter function. Learn to code — free 3,000-hour curriculum


const controller = {
init() {
// set the current car to the first one in the list
model.currentCar = model.cars[0];

// tell the views to initialize


carListView.init();
carView.init();
},

getCurrentCar() {
return model.currentCar;
},

getCars() {
return model.cars;
},

// set the currently selected car to the object that's passed in


setCurrentCar(car) {
model.currentCar = car;
},

// increment the counter for the currently-selected car


incrementCounter() {
model.currentCar.clickCount++;
carView.render();
},
Search 10,900+ tutorials  Forum Donate
};

Learn to code — free 3,000-hour curriculum


// Let's goooo!
controller.init();

MVC Frameworks
JavaScript has grown in popularity, and it's taken over the
backend in recent years. More and more full-blown JavaScript
applications have opted for the MVC architecture pattern in one
way or another.

Frameworks come and go, but what has been constant are the ADVERTISEMENT

concepts borrowed from the MVC architecture pattern.

Some of the early frameworks that applied these concepts were


KnockoutJS, Django, and Ruby on Rails.

Conclusion

TheSearch
most10,900+
attractive concept of the MVC pattern is separation of
tutorials Forum Donate
concerns. Learn to code — free 3,000-hour curriculum

Modern web applications are very complex, and making a change


can sometimes be a big headache.

Managing the frontend and backend in smaller, separate


components allows for the application to be scalable,
maintainable, and easy to expand.

**If you want to take a look at the Car Clicker app, the code is
available on GitHub or checkout the live version here.**

🌟 Thank you for reading this far! 🌟

Rafael D. Hernandez
Web Developer | Global Language Translations Lead at @freeCodeCamp
If you read
Search this far,
10,900+ thank the author to show them you care.
tutorials Say Thanks Forum Donate

Learn to code — free 3,000-hour curriculum

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people
get jobs as developers. Get started
ADVERTISEMENT

#1 Rooftop PV Design Tool


Reduce layout time by up to 80% and ensure real-world
precision.

PVcase Learn More

freeCodeCamp is a donor-supported tax-exempt 501(c)(3) charity


Trending Guides
organization (United States Federal Tax Identification Number: 82-
0779546) Date Formatting in JS Java Iterator Hashmap
Cancel a Merge in Git What is a Linked List?
Install Java in Ubuntu Python Ternary Operator
Our mission:
Searchto help people
10,900+ learn to code for free. We accomplish
tutorials Full Stack Career Guide PythonForum
Sort Dict by Key
Donate
this by creating thousands of videos, articles, and interactive coding Smart Quotes Copy/Paste JavaScript Array Length
Learn to code — free 3,000-hour curriculum
lessons - all freely available to the public. Sets in Python Kotlin vs Java
SQL Temp Table HTML Form Basics
Donations to freeCodeCamp go toward our education initiatives, and
Comments in YAML Pandas Count Rows
help pay for servers, services, and staff.
Python End Program Python XOR Operator
You can make a tax-deductible donation here . Python Dict Has Key Python List to String
Exit Function in Python String to Array in Java
Python Import from File Parse a String in Python
Python Merge Dictionaries Copy a Directory in Linux
Reactive Programming Guide Center Text Vertically CSS
What’s a Greedy Algorithm? Edit Commit Messages in Git

Mobile App

Our Charity

About Alumni Network Open Source Shop Support Sponsors Academic Honesty Code of Conduct Privacy Policy Terms of Service

Copyright Policy

You might also like