Change the template
Open index.html
and find <template id="cart-item-template">
, update the code so it will look like:
<template id="cart-item-template">
<li>
<p class='qty'>${qty}</p>
<p class='name'>${name}</p>
<p class='price'>${price}</p>
<p class='toolbar'>
<a href="#" class="delete-button">
🗑️
</a>
</p>
</li>
</template>
Change the implementation
Open components/CartItem.js
and we will work with the connectedCallback()
method.
Add the following local function:
function interpolate (str, params) {
let names = Object.keys(params);
let values = Object.values(params);
return new Function(...names, `return \`${str}\`;`)(...values);
}
Delete the following lines:
this.appendChild(content);
this.querySelector(".qty").textContent = `${item.quantity}x`;
this.querySelector(".name").textContent = item.product.name;
this.querySelector(".price").textContent = `$${item.product.price.toFixed(2)}`;
Replace them with:
const template = document.getElementById("cart-item-template");
this.innerHTML = interpolate(template.innerHTML, {
qty: `${item.quantity}x`,
price: `$${item.product.price.toFixed(2)}`,
name: item.product.name
});
The final code for the file should look like:
import { removeFromCart } from "../services/Order.js";
export default class CartItem extends HTMLElement {
constructor() {
super();
}
connectedCallback() {
const item = JSON.parse(this.dataset.item);
this.innerHTML = ""; // Clear the element
function interpolate (str, params) {
let names = Object.keys(params);
let values = Object.values(params);
return new Function(...names, `return \`${str}\`;`)(...values);
}
const template = document.getElementById("cart-item-template");
this.innerHTML = interpolate(template.innerHTML, {
qty: `${item.quantity}x`,
price: `$${item.product.price.toFixed(2)}`,
name: item.product.name
});
this.querySelector("a.delete-button").addEventListener("click", event => {
removeFromCart(item.product.id);
})
}
}
customElements.define("cart-item", CartItem);