I am working on understanding Knockout. While developing I had a problem with computed variable in this scenario called total. It does not seem to update in my UI interface despite binding to the total variable from the UI. It also had an effect of hiding the other controls at the back of the bound total control , in this case my select drop down was hidden. Please am I doing something wrong. this is my Javascript
<head><title>Hello Knockout</title></head>
<body>
<p>
<input type="text" data-bind="value : Listprice , valueUpdate : 'afterkeydown'" />
<span data-bind="text : formatCurrency(Listprice)"></span>
<span data-bind= "text : total"/>
<select data-bind="options : color , optionsText : 'name' , value:selectedColor, optionsCaption : 'Choose item..'" />
<span data-bind="text : selectedColor" />
<script type="text/javascript" src="Scripts/knockout-2.1.0.debug.js"></script>
<script type="text/javascript" src="Scripts/jquery-1.8.1.min.js"></script>
<script type="text/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"
};
$(function () {
var Colored = function (id, name) {
this.id = ko.observable(id),
this.name = ko.observable(name)
};
var vm = {
id: ko.observable(data.Id),
saleprice: ko.observable(data.SalePrice),
Listprice: ko.observable(data.ListPrice),
ShortDesc: ko.observable(data.Description),
color: ko.observableArray([
new Colored(1, "Black"),
new Colored(2, "Red"),
new Colored(3, "Blue")
]),
selectedColor: ko.observable(),
quantity: ko.observable(2)
};
vm.total = ko.computed(function () {
return this.Listprice,10 ? this.ListPrice: 0;
}, vm);
vm.formatCurrency = function (value) {
return "$" + value();
};
ko.applyBindings(vm);
});
</script>
</body>
Make sure you always format your spans like this:
rather than
EDIT:
Also
Listpriceis an observable, which is a function. Make sure you invoke it using () if you want to get the current value:Here is a working fiddle you can play with: http://jsfiddle.net/jearles/vDmP2/