Chapter 10. A Practical Example
For this final chapter, I thought it would be a good idea to see several of the things that have been demonstrated in small examples throughout the previous chapters. What better way to do that than with a shopping cart?
In previous examples, the HTML and JavaScript code have often been presented in a single example. Because this HTML and JavaScript is slightly larger than previous examples, it has been broken up into several small JavaScript files and one HTML file.
Building a Shopping Cart
Let’s begin by defining the goals of the shopping cart:
- Include a category selection to allow easy filtering of products
- Display a list of products for a given category
- See how many items are currently in the shopping cart
- Add an item to the cart
- Remove an item from the cart
- Display the running total of items in the cart
- Include some simple animations when adding/removing from the cart
I think that covers the core features of a typical shopping cart. By looking at these features, I see an immediate need for three arrays:
- List of categories with their available items.
- List of available products for the active category.
- List of items the user is interested in purchasing.
In addition to these three arrays, we want to keep track of the current running total.
Example 10-1 shows the HTML that covers the shopping cart’s features.
Example 10-1. HTML for shopping cart
<!DOCTYPE html>
<html>
<head>
<title>
Yet Another Shopping Cart</title>
</head>
<body>
<div
Get Knockout.js now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.