I have the following code:
// First we define our gift class, which has 2 properties:
// a Title and a Price.
// We use knockout js validation to ensure that the values input are suitable/
function Gift(item)
{
var self = this;
self.Title = ko.observable(item.Title);
// attach some validation to the Title property courtesy of knockout js validation
self.Title.extend({
required: true,
minLength: 3,
pattern: {
message: 'At least ',
params: '^[a-zA-Z]+\s?[a-zA-Z]*'
}
});
self.Price = ko.observable(item.Price);
self.Price.extend({required:true,number:true,min:0.1,max:1000});
};
var viewModelForTemplated =
{
gifts: ko.observableArray(), // gifts will be an array of Gift classes
addGift: function ()
{
this.gifts.push(new Gift({ Title: "", Price: "" }));
},
removeGift: function (gift)
{
this.gifts.remove(gift);
},
totalCost: ko.computed(function () {
if (typeof gifts == 'undefined')
return 0;
var total = 0;
for (var i = 0; i < gifts().length; i++)
{
total += parseFloat(gifts()[i].Price());
};
return total;
})
}
$(document).ready(function ()
{
// load in the data from our MVC controller
$.getJSON("gift/getdata", function (allGifts)
{
var mappedgifts = $.map(allGifts, function (gift)
{
return new Gift(gift);
});
viewModelForTemplated.gifts(mappedgifts);
});
ko.applyBindings(viewModelForTemplated, $('#templated')[0]);
}
and then (above the script)
<div id="templated">
<table >
<tbody data-bind="template: { name: 'giftRowTemplate', foreach: gifts }"></tbody>
</table>
<script type="text/html" id="giftRowTemplate">
<tr>
<td>Gift name: <input data-bind="value: Title"/></td>
<td>Price: \$ <input data-bind="value: Price"/></td>
<td><a href="#" data-bind="click: function() { viewModelForTemplated.removeGift($data) }">Delete</a></td>
</tr>
</script>
<p>Total Cost <span data-bind="text: totalCost"></span> </p>
<button data-bind="click: addGift">Add Gift</button>
<button data-bind="click: save">Save</button>
</div>
The totalCost method only runs once, when the gifts array is empty, and I can push or remove items onto the observableArray() no problem but nothing fires .
How do I get the span referring to totalCost to update? I bet it's something simple :)
Thanks for your help.