O'Reilly logo

Knockout.js by Jamie Munro

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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>
<html>
<head> 
    <title>Yet Another Shopping Cart</title>
</head>
<body> 

    <div 

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required