Knockout - MVVM basics - revealing module pattern

by jwstott

HTML

<script src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-2.2.0.js"></script>
<span data-bind="text: shortDesc"></span>
<div data-bind="text: description" class="descArea"></div>
<span data-bind="text: formatCurrency(salePrice)"></span>

CSS

body{
    margin: 10px;
}
span {
    margin: 0 10px 0 0;
}
.descArea{
    padding:10px;
    background-color: lightgray;
    border: black 1px solid;
    -webkit-border-radius: 15px;
    -moz-border-radius: 15px;
    border-radius: 15px;
}

JavaScript

// The Model
var data = {
    "Id": 1001,
    "SalePrice": 1649.01,
    "ListPrice": 2199.00,
    "ShortDesc": "Taylor 314CE",
    "Description": "Taylor 314-CE Left-Handed Grand Auditorium Acoustic-Electric Guitar"
};

// The ViewModel -  revealing module pattern
var viewmodel = function (){
    var id = ko.observable(data.Id),
        salePrice = ko.observable(data.SalePrice),
        listPrice = ko.observable(data.ListPrice),
        shortDesc = ko.observable(data.ShortDesc),
        description = ko.observable(data.Description),
        formatCurrency = function(value) {
            return "$" + value().toFixed(2);
        }
    return{
        id : id,
        salePrice : salePrice,
        listPrice : listPrice,
        shortDesc : shortDesc,
        description : description,
        formatCurrency : formatCurrency
    }
};

// Bind the ViewModel to the View using Knockout
ko.applyBindings(new viewmodel());