我收到错误“无法解析绑定(bind),ReferenceError:‘calculateTotalPrice’未定义; 绑定(bind)值:点击:calculateTotalPrice
下面是我的简单代码片段
<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>
但是当我这样做时,单击并提供函数名称,会出现上面的错误。
这是我的 View 模式
函数 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);
}
}
在文档准备好后,我进行 AJAX 调用,从服务器获取数据(这工作正常),如下所示
$(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);
}
});
});
任何人都可以帮我解决我在这里做错的事情吗(我打赌我是)?提前谢谢。
最佳答案
当您处于 foreach
循环中时,Knockout 期望数据绑定(bind)中的任何函数或属性在数组的条目中定义,在本例中是 中的值价格_数量
。要访问保存数组的对象中定义的函数和属性,请使用 $parent
标识符。因此,要在循环中使用 calculateTotalPrice
,您需要执行以下操作:
<li>
<button data-bind="click: $parent.calculateTotalPrice">CLICK THIS TO UPDATE TOTAL</button>
</li>
View 模型:
function ViewPriceObjectOnWeb(d) {
var self = this;
self.price_quantity = ko.observableArray(d);
self.totalCost = ko.observable(100);
self.calculateTotalPrice = function (p) {
var tp = self.totalCost() + p;
self.totalCost(tp);
};
}
工作示例(使用硬编码价格):http://jsfiddle.net/jonhopkins/fn7vc/2/
关于knockout.js - 按钮单击功能的数据绑定(bind)给出了 knockout 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13631216/