Skip to content

Instantly share code, notes, and snippets.

@mvaldes14
Created September 5, 2018 21:49
Show Gist options
  • Save mvaldes14/70141b5c5498205ee5972203339e90cb to your computer and use it in GitHub Desktop.
Save mvaldes14/70141b5c5498205ee5972203339e90cb to your computer and use it in GitHub Desktop.
Booklist - app.js
// Book
class Book {
constructor(title, author, isbn) {
this.title = title;
this.author = author;
this.isbn = isbn;
}
}
// UI Control
class UI {
createElement(element, obj) {
const el = document.createElement(element)
el.innerHTML = `
<th> ${obj.title} </th>
<th> ${obj.author} </th>
<th> ${obj.isbn} </th>
<th> <a hre='#' class='delete-me'> X</a> </th>
`
return el
}
validate(title, author, isbn) {
if (title === '' || author === '' || isbn === '') {
alert('Empty fields')
return false
} else {
return true
}
}
clearFields() {
document.getElementById('title').value = ''
document.getElementById('author').value = ''
document.getElementById('isbn').value = ''
}
deleteElement(target) {
target.parentElement.parentElement.remove()
}
}
class Store {
static getBooks() {
let allBooks
if (localStorage.getItem('BookList') === null) {
allBooks = []
} else {
allBooks = JSON.parse(localStorage.getItem('BookList'))
}
return allBooks
}
static addBook(book) {
const allBooks = Store.getBooks()
allBooks.push(book)
localStorage.setItem('BookList', JSON.stringify(allBooks))
}
static removeBook(isbn) {
const allBooks = Store.getBooks()
allBooks.forEach( (book, index) => {
if(book.isbn === isbn) {
books.splice(index, 1)
}
})
localStorage.setItem('BookList', JSON.stringify(allBooks))
}
static displayBooks() {
const books = Store.getBooks()
const booklist = document.getElementById('book-list')
const row = new UI()
books.forEach(book => {
let newRow = row.createElement('tr', book)
booklist.appendChild(newRow)
});
}
}
// DOM Loaded
document.addEventListener('DOMContentLoaded', () => {
Store.displayBooks()
})
// Form Listener
document.getElementById('book-form').addEventListener('submit', e => {
const title = document.getElementById('title').value,
author = document.getElementById('author').value,
isbn = document.getElementById('isbn').value;
const book = new Book(title, author, isbn)
const row = new UI()
if (row.validate(title, author, isbn)) {
const newbook = row.createElement('tr', book)
const booklist = document.getElementById('book-list')
booklist.appendChild(newbook)
row.clearFields(title, author, isbn)
Store.addBook(book)
} else {
return null;
}
e.preventDefault()
})
// Clear from Table
document.getElementById('book-list').addEventListener('click', e => {
const row = new UI()
if (e.target.className === 'delete-me') {
row.deleteElement(e.target)
Store.removeBook(e.target.parentElement.previousElementSibling.textContent)
}
e.preventDefault()
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment