After implementing a Book class which includes a method to add a single object to an array upon clicking a button, I noticed that when the button is clicked, it adds the button itself rather than the expected object.
See the code snippet below:
class Book {
constructor(title, author, year, poster){
this.title = title;
this.author = author;
this.year = year
this.poster = poster
}
addToFavourite(){
favouriteBooks.push(this)
}
}
const favouriteBooks = []
const booksList = [ new Book('you don\'t know js', ' Kyle Simpson', 2014, 'https://images-na.ssl-images-amazon.com/images/I/41T5H8u7fUL._SX331_BO1,204,203,200_.jpg'),
new Book('javascript the definitive guide', 'David Flanagan', 1996, 'https://images-na.ssl-images-amazon.com/images/I/51wijnc-Y8L._SX379_BO1,204,203,200_.jpg'),
new Book('Eloquent JavaScript', 'Marijn Haverbeke', 2011, 'https://eloquentjavascript.net/img/cover.jpg')
]
const renderBooks = (booksToRender)=>{
booksToRender.forEach(book =>{
//elements to be created
const bookContainer = document.createElement('article')
const posterContainer = document.createElement('div')
const poster = document.createElement('img')
const bookTitle = document.createElement('h2')
const bookYear = document.createElement('p')
const bookAuthor = document.createElement('h3')
const addToFavouriteBtn = document.createElement('button')
//elements setup
addToFavouriteBtn.addEventListener('click', book.addToFavourite)
poster.src = book.poster
bookTitle.textContent = book.title
bookYear.textContent = book.year
bookAuthor.textContent = book.author
addToFavouriteBtn.textContent = 'Add to favourite'
//elements render
posterContainer.append(poster)
bookContainer.append(posterContainer, bookTitle, bookYear, bookAuthor, addToFavouriteBtn)
document.querySelector('main').append(bookContainer)
})
}
renderBooks(booksList)