Hey guys, today I am writing about one of the most scary kind of feature in javascript which is objects or object oriented programming. As we all know, objects are the most used data types in javascript programming and they are no doubt the most closest representation of real world variables like for example if I want to buy a dress which looks somewhat like this:
I can easily explain that in terms of an object:
const dress = {
color: "Red",
fabric: "silk",
length: "100m",
size: "medium"
}
We know, that we can create classes out of these objects and manipulate them according to our program, you can read in more detail about the basic concepts of object oriented programming here: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object-oriented_JS
However, in this article I will discuss a practical usecase/project where we will actually make use of the classes and methods (inside the classes) and learn how we can simplify our code using the oop part of javascript and also you'll get to know that once you understand the practical approach of objects then they will become your best friends in programming.
So, I am now building a small Movies Database application which will allow us to create a list of movies, delete them and display the entries..all this is done using classes and objects.
First of all create a new index.html file. I will be using bootswatch and font awesome (for icons). The basic structure of our index file looks like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" />
<link rel="stylesheet" href="https://bootswatch.com/4/yeti/bootstrap.min.css" />
<link rel="stylesheet" href="/styles.css" />
<title>Movies Database App</title>
</head>
<body>
<div class="container mt-4">
<h1 class="display-4 text-center">
<i class="fas fa-video" style="color: blue;"></i> Movies<span class="text-primary">Database</span>List
</h1>
<form id="movie-form">
<div class="form-group">
<label for="title">Title</label>
<input type="text" id="title" class="form-control" />
</div>
<div class="form-group">
<label for="author">Director</label>
<input type="text" id="director" class="form-control" />
</div>
<div class="form-group">
<label for="isbn">Year</label>
<input type="text" id="year" class="form-control" />
</div>
<input type="submit" value="Add Movie" class="btn btn-primary btn-block" />
</form>
<table class="table table-striped mt-5">
<thead>
<tr>
<th>Title</th>
<th>Director</th>
<th>Year</th>
<th></th>
</tr>
</thead>
<tbody id="movie-list"></tbody>
</table>
</div>
<script src="/script.js"></script>
</body>
</html>
After we are done with the index.html file, now we will move to the script.js file and do all the javascript logic there.
First we will create a Movie class which will enable us to add movies later on, this class will have a constructor function which is used to define and initialize the objects and their features, this constructor will consist a title, director and the year in which the movie was released:
class Movie {
constructor(title, director, year) {
this.title = title
this.director = director
this.year = year
}
}
To start with, we have created a defaultMovies array so that we have something to display before the user starts adding his/her records:
const defaultMovies = [
{
title: 'Jurassic Park',
director: 'John Doe',
year: '1990'
},
{
title: 'The Dead Pool',
director: 'Mathew Albison',
year: '2014'
}
]
Next, we will create a UI class where we will handle the display, adding and deleting movies functions in the DOM:
class UI{
static displayMovies = () =>{
defaultMovies.forEach(movie=>UI.addMovieToList(movie))
}
static addMovieToList = (movie) => {
const list = document.getElementById('movie-list');
const row = document.createElement('tr')
row.innerHTML=`
<td>${movie.title}</td>
<td>${movie.director}</td>
<td>${movie.year}</td>
<td><a href="#" class="btn btn-danger btn-sm delete">X</a></td>`
list.appendChild(row)
}
static deleteMovie(movie){
if(movie.classList.contains('delete')){
movie.parentElement.parentElement.remove()
}
}
}
UI.displayMovies()
Now, we will deal with the 'Add Movie' button, when user enters the input values and clicks the add button then the following addAMovie function will be called which will store the input values in its respective variables and instantiate a new Movie object and will add the movie object to the UI class:
// Event: Add a Movie
document.querySelector('#movie-form').addEventListener('submit', addAMovie, false)
function addAMovie(e) {
// prevent actual submission
e.preventDefault()
// Get Form Values
const title =document.querySelector('#title').value;
const director =document.querySelector('#director').value;
const year =document.querySelector('#year').value;
// Instantiate a new Book object
const movie = new Movie(title,director,year)
// Add book object to UI
UI.addMovieToList(movie)
UI.showAlert("Movie Added", 'success')
UI.clearFields();
}
Now, we have to take care of clearing the fields after user has added the record, this is done by defining a clearFields method in the UI class:
static clearFields(){
document.querySelector('#title').value="";
document.querySelector('#director').value="";
document.querySelector('#year').value="";
}
We will show alert messages on adding, deleting and invalid input values through a showAlert method in the UI class which will take two arguments as input, first the message to be shown based upon user's action and the class to be added on the alert.
static showAlert(message,className){
const div = document.createElement('div')
div.innerText = message
div.className = `alert alert-${className}`
document.getElementById('movie-form').prepend(div)
setTimeout(()=>document.querySelector('.alert').remove(),2000)
}
We can also add a validation in the addAMovie method if user enters any record with empty input values:
if(!title || !director || !year){
UI.showAlert("Please enter correct details", "danger")
return
}
This brings us to the end of this simple application that demonstrates the use of classes and methods in an oop manner.
I hope you will find this application useful.
Happing coding and have a nice day.
Disclaimer: I know this may not be the best approach for this problem but here, the purpose is only to demonstrate the use of objects and classes that's why I have picked up this solution. You are always welcome to come up with your solutions and can scale the application as much as you like.
Top comments (0)