I'm struggling with the following issue: I must use basically just JS for creating a button.
//btn add
let button_add = document.createElement("button");
let button_add_class = button_add.className = "btn-add";
let button_add_click = button_add.setAttribute("onclick", "addBookToShoppingCart(first)");
let buttonText1 = document.createTextNode("Add to Shopping Cart");
button_add.appendChild(buttonText1);
this.mainBookScreen.appendChild(button_add);
The button need to call the addBookToShoppingCart(first)
method, which is in the ShoppingCart
class.
class ShoppingCart{
addBookToShoppingCart(bookObject) {
alert('Hello World!');
}
}
If I click to the button I get the following error message in the browser's console:
Uncaught ReferenceError: addBookToShoppingCart is not defined
at HTMLButtonElement.onclick
Edit: My latest code is here:
class ShoppingCart{
addBookToShoppingCart(bookObject) {
alert('Hello World!');
}
}
class Shop {
constructor() {
this.shoppingCart = new ShoppingCart("Shopping Cart");
this.mainBookScreen = document.getElementById("mainBookScreen");
}
addBookToScreen(book) {
//btn add
const button_add = document.createElement("button");
button_add.classList.add("btn-add");
button_add.textContent = "Add to Shopping Cart";
button_add.addEventListener("click", function(){this.shoppingCart.addBookToShoppingCart(first)});
this.mainBookScreen.appendChild(button_add);
}
}
class Book {
//book constructors
}
let first = "TEST";
let book = [];
book[0] = new Book("bla1", "bla2", "bla3");
boook[1] = new Book("ble1", "ble2", "ble3");
const shop = new Shop();
shop.addBookToScreen(book[0]);
shop.addBookToScreen(book[1]);
Error message in browser if I click to the button:
Cannot read property 'addBookToShoppingCart' of undefined at HTMLButtonElement.