Knockout - MVVM basics - function
by beewayne
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
// 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
var viewmodel = function (){
this.id = ko.observable(data.Id);
this.salePrice = ko.observable(data.SalePrice);
this.listPrice = ko.observable(data.ListPrice);
this.shortDesc = ko.observable(data.ShortDesc);
this.description = ko.observable(data.Description);
this.formatCurrency = function(value) {
return "$" + value().toFixed(2);
};
};
// Bind the ViewModel to the View using Knockout
ko.applyBindings(new viewmodel());