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:

  1. List of categories with their available items.
  2. List of available products for the active category.
  3. 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>
    <title>Yet Another Shopping Cart</title>


Get Knockout.js now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.