Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function attachEvents() {
- const LoadCreateURL = "https://fisher-game.firebaseio.com/catches.json"
- const UpdateDeleteURl = id => `https://fisher-game.firebaseio.com/catches/${id}.json`
- const catches = document.getElementById("catches")
- const crudOperation = {
- load: loadCatchesAsync,
- add: addCatch,
- update: updateCatchAsync,
- delete: deleteCatchAsync
- }
- window.addEventListener("click", (e) => {
- let operation = e.target.className
- if (operation === "load" ||
- operation === "add" ||
- operation === "update" ||
- operation === "delete") {
- crudOperation[operation].call(this, e)
- }
- })
- async function loadCatchesAsync() {
- await fetch(LoadCreateURL)
- .then(x => x.json())
- .then(x => displayAllCatches(x))
- .catch(e => console.log(e))
- }
- function displayAllCatches(obj) {
- for (const catchId of Object.keys(obj)) {
- let div = document.createElement("div")
- div.classList.add("catch")
- div.setAttribute("data-id", `${catchId}`)
- div.innerHTML = `<label>Angler</label>
- <input type="text" class="angler" value="${obj[catchId].angler}" />
- <hr>
- <label>Weight</label>
- <input type="number" class="weight" value="${obj[catchId].weight}" />
- <hr>
- <label>Species</label>
- <input type="text" class="species" value="${obj[catchId].species}" />
- <hr>
- <label>Location</label>
- <input type="text" class="location" value="${obj[catchId].location}" />
- <hr>
- <label>Bait</label>
- <input type="text" class="bait" value="${obj[catchId].bait}" />
- <hr>
- <label>Capture Time</label>
- <input type="number" class="captureTime" value="${obj[catchId].captureTime}" />
- <hr>
- <button class="update">Update</button>
- <button class="delete">Delete</button>`
- catches.appendChild(div);
- }
- }
- function addCatch() {
- const inputs = document.querySelectorAll("aside fieldset#addForm input");
- let obj = JSON.stringify(getDataFromInputForm(inputs))
- fetch(LoadCreateURL,
- {
- method: "post",
- body: obj
- })
- .catch()
- }
- async function updateCatchAsync(e) {
- let divCatch = e.target.parentNode
- let catchId = divCatch.attributes["data-id"].value
- let obj = getDataFromInputForm(divCatch.getElementsByTagName("input"))
- await fetch(UpdateDeleteURl(catchId),
- {
- method: "put",
- body: JSON.stringify(obj)
- })
- .catch(e => console.error(e))
- }
- async function deleteCatchAsync(e) {
- let catchId = e.target.parentNode.attributes["data-id"].value
- await fetch(UpdateDeleteURl(catchId),
- {
- method: "delete",
- })
- .catch(e => console.error(e))
- }
- function getDataFromInputForm(input) {
- let obj = {};
- [...input].map(e => (obj[e.className] = e.value));
- return obj;
- }
- }
- attachEvents();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement