Hi learning JavaScript OOP, I got some questions. Following some online tutorials, I created ToDo list project using DOM and similar Book list project with OOP concept learned.
They are pretty similar in a way that how users key in values into input fields and press submit button then the values keyed in will be added as a row in html.
But my question is that why we use OOP - creating classes such as book list, ui classes since they also create DOM stuff. Or the question should be what benefits using OOP for such project?
Below is the code for Book list project
// Book Constructor
function Book(title, author, isbn) {
this.title = title;
this.author = author;
this.isbn = isbn;
}
// UI Constructor
function UI() {
}
// Add Book To List
UI.prototype.addBookToList = function(book) {
const list = document.getElementById('book-list');
// Create tr element
const row = document.createElement('tr');
// Insert cols
row.innerHTML = `
<td>${book.title}</td>
<td>${book.author}</td>
<td>${book.isbn}</td>
<td><a href="#" class="delete">X</a></td>
`;
list.appendChild(row);
}
// Clear Fields
UI.prototype.clearFields = function() {
document.getElementById('title').value = '';
document.getElementById('author').value = '';
document.getElementById('isbn').value = '';
}
// Event listeners
document.getElementById('book-form').addEventListener('submit', (e) => {
// Get form values
const title = document.getElementById('title').value,
author = document.getElementById('author').value,
isbn = document.getElementById('isbn').value
// Instantiate book
const book = new Book(title, author, isbn);
// Instantiate UI
const ui = new UI();
// Add book to list
ui.addBookToList(book);
// Clear fields
ui.clearFields();
e.preventDefault();
});