Knockout - MVVM basics - revealing module pattern
HTML
<script src="https://github.com/downloads/SteveSanderson/knockout/knockout-2.0.0.debug.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
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
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());