I get error of “Unable to parse Binding, ReferenceError: ‘calculateTotalPrice’ is undefined;
Bindings value: click: calculateTotalPrice
below is my simple code snippet
<div style="background-color:black; color:white; overflow:scroll; height:350px;width:300px" id="pricesku">
<span id="total" data-bind="text: totalCost"></span>
<ul data-bind="foreach: price_quantity" style="list-style-type:none;">
<li>
<button data-bind="click: calculateTotalPrice(price)">CLICK THIS TO UPDATE TOTAL</button>
</li>
</ul>
</div>
But when I do, click and provide function name, get an error above.
This is my View Modal
function ViewPriceObjectOnWeb(d) {
this.price_quantity = ko.observableArray(d);
this.totalCost = ko.observable(100);
this.calculateTotalPrice = function (p) {
var tp = this.totalCost() + p;
//$('#total').text(tp);
}
}
and on document ready i make AJAX Call that brings Data from server (this works fine) as below
$(document).ready(function () {
var sku = "abcd";
$.ajax({
url: "/api/values?clientSKU=" + sku, //this would give SKU/Price collection as JSON Serialized object from .NET/Server Side
dataType: "json",
asyc: false,
type: "get",
success: function (msg) {
var skuandprice = $.parseJSON(msg);
ko.applyBindings(new ViewPriceObjectOnWeb(skuandprice), document.getElementById('pricesku'));
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus + ' ' + errorThrown);
}
});
});
Can anyone help me what I am doing wrong here(i bet i am)? Thx in advance.
When you are inside a
foreachloop, Knockout expects any functions or properties in the data-bind to be defined within the entries of the array, which in this case are the values inprice_quantity. To access functions and properties that are defined in the object that holds the array, you use the$parentidentifier. So to usecalculateTotalPriceinside your loop, you need to do:The view model:
Working example (using hard-coded prices): http://jsfiddle.net/jonhopkins/fn7vc/2/