Working with List

Binding dropdown

In this section, we'll make a small shopping cart app. We'll have a list of products, so that user can choose from. We have a list of cart item that display item name and quanity. In that list, we have a button to remove cart item from the list.

First of all, we have some bootstrap HTML template for our app. In the template, we have a select box of products and we have to table to display cart items. After that, initialize some products within a ViewModel class
  1. function ShoppingCartViewModel() {  
  2.     var self = this;  
  3.       
  4.     // Temporarily hard code  
  5.     // We should query from server  
  6.     this.products = [  
  7.         { name: 'iPhone', price: 900 },  
  8.         { name: 'Samsung galaxy', price: 850 },  
  9.         {name: 'Google Pixel', price: 800 },  
  10.         {name: 'Google nexus', price: 750 }  
  11.     ];  
  12.   
  13.     this.selectedItem = html.observable(this.products[0]);  
  14. }  
  15.   
  16. var vm = new ShoppingCartViewModel();  
Then show all product to select box using built-in dropdown component.
  1. html('#prod').dropdown(vm.products, vm.selectedItem, 'name''name');  
Is that simple for binding select box/dropdown? We provide the function the list of products, selected items, display field, value field. All the magic happens behind the scence.
1
X
1
2
3
4
5
6
7
8
9
10
11
12
13
<h3><i class="glyphicon glyphicon-shopping-cart"></i> Shopping cart</h3>
<div class="row" style="margin-bottom: 10px;">
    <div class="col-sm-6"><select class="btn btn-primary form-control" id="prod"></select></div>
    <div class="col-sm-3"><button id="add" class="btn btn-primary">Add</button></div><br />
</div>
<table id="shCart" class="table">
    <tbody>
    </tbody>
</table>
X

Shopping cart