Knockoutjs Hybrid Example

Example of having hybrid static html together with knockout view models. Here buy buttons appear that can put products to a cart. Id's exist in data attributes in the static html which are coupled with data in javascript.

by spoike

HTML

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css">
<div class="productView" data-prodid="1">
    <h2>Vacuum Cleaner</h2>
    <div class="info" data-bind="template: {name: 'product-template'}"></div>
</div>
<div class="productView" data-prodid="2">
    <h2>Clean Sweeper</h2>
    <div class="info" data-bind="template: {name: 'product-template'}"></div>
</div>
<h2>Cart</h2>
<ul id="cart" data-bind="foreach: items">
    <li>
        <span class="name" data-bind="text: name"></span> $<span data-bind="text: price.toFixed(2)"></span>
    </li>
</ul>
<script type="text/html" id="product-template">
    $<span data-bind="text: data.price.toFixed(2)"></span> 
    <span class="btn btn-mini" data-bind="click: buy">Buy</span>
</script>

CSS

.productView {
    border: 1px black solid;
    border-radius: 5px;
    padding: 5px;
    margin: 15px;
}
.name {font-weight: bold;}
h2 {
    font-family: Arial, sans-serif;
    line-height: 1em;
    font-size: 20px;
}

JavaScript

var productViewModel = function(data, cartVm) {
    var self = this;
    
    self.cartVm = cartVm;
    
    self.data = data;
    
    self.buy = function() {
        self.cartVm.add(data);
    };
}

var cartViewModel = function() {
    var self = this;
    
    self.items = ko.observableArray([]);
    
    self.add = function(data) {
        self.items.push(data);
    };
}

var products = {
    '1': {name: "vacuum cleaner", price: 12.4},
    '2': {name: "clean sweeper", price: 14.99}
}

var cartVm = new cartViewModel();
ko.applyBindings(cartVm, document.getElementById('cart'));

$('.productView').each(function() {

    var id = $(this).data('prodid');
    ko.applyBindings(new productViewModel(products[id], cartVm), this);

});