Coder's Cat

Svelte Demo: Movie Seat Booking

2021-12-03

Let’s continue our journey of learnning Svelte and JavaScript 😊

This time, we will build a small Web application for movie seat booking. After finishing, we will have a cute demo looks like this:

Svelte onMount

Because we need to keep the selected seat status after page refreshing, we need to use localStorage to store selected seat indexes , then reloading them when page in reloaded. In Svelte, we need to use onMount to hook up a function to reload data:

onMount(() => {
populateUI();
});

Restore state and event hookup

The function populateUI will do 3 things:

  1. reload selected seats and updated seats count
  2. update selected movie price
  3. hook up function for each movie seat click event
// Get data from localstorage and populate UI
function populateUI() {
const selectedSeats = JSON.parse(localStorage.getItem("selectedSeats"));

let num = 0;
if (selectedSeats !== null && selectedSeats.length > 0) {
allSeats().forEach((seat, index) => {
if (selectedSeats.indexOf(index) > -1) {
seat.classList.add("selected");
num += 1;
}
});
}
count = num;

const selectedMovieIndex = localStorage.getItem("selectedMovieIndex");

if (selectedMovieIndex !== null) {
document.getElementById("movie").selectedIndex = selectedMovieIndex;
movieIndex = selectedMovieIndex;
}
moviePrice = document.getElementById("movie").value;

// Seat click event
const container = document.querySelector('.container');
container.addEventListener("click", (e) => {
if (
e.target.classList.contains("seat") &&
!e.target.classList.contains("occupied")
) {
e.target.classList.toggle("selected");

updateSelected();
}
});
}

If we changed the selected movie, we need to update the price for a single movie , so another event hookup in HTML:

<div class="movie-container">
<span>Pick a movie:</span>
<select id="movie" on:change={handleMovieSelect}>
<option value="10">Avengers: Endgame ($10)</option>
...
</select>
</div>

The logic for total price

The function updateSelected will update new selected movies count. Here, a tricky part is use css selector to get elements:

// Update total and count
function updateSelected() {
const selectedSeats = document.querySelectorAll(".row .seat.selected");

const seatsIndex = [...selectedSeats].map((seat) =>
[...allSeats()].indexOf(seat)
);

localStorage.setItem("selectedSeats", JSON.stringify(seatsIndex));
count = selectedSeats.length;
}

How do we calculate the total price of movies? A nice feature comes from Svelte may help us reduce code complexity :

$:{
total = count * moviePrice;
}

With this snippet, it means whenever count and moviePrice changed, total will be updated accordingly , nice and simple!


That’s all, the whole code for this demo is at: sveltejs-apps (github.com)

Join my Email List for more insights, It's Free!😋