Binding Form Data
At components/OrderPage.js
add the following property
#user = {
name: "",
phone: "",
email: ""
}
And within the class, create a new method
setFormBindings(form) {
form.addEventListener("submit", event => {
event.preventDefault();
alert(`Thanks for your order ${this.#user.name}. ${this.#user.email ? "We will be sending you the receipt over email." : "Ask at the counter for a receipt."}`);
this.#user.name = "";
this.#user.email = "";
this.#user.phone = "";
// TODO: sent user and cart's details to the server
});
// Set double data binding
Array.from(form.elements).forEach(element => {
if (element.name) {
element.addEventListener("change", event => {
this.#user[element.name] = element.value;
})
}
});
this.#user = new Proxy(this.#user, {
set(target, property, value) {
target[property] = value;
form.elements[property].value = value;
return true;
}
})
}
Finally, call it from render
this.setFormBindings(this.root.querySelector("form"));