现在我有以下JSON文档:
[
{
"price":"1.0",
"shares":13
},
{
"price":"2.0",
"shares":5
},
{
"price":"3.0",
"shares":24
}
]如果有人想要20股,我想返回20股可能的最低价格。在这种情况下,它是:
13股,每股1美元(13美元)
5股,2美元(10美元)
2股,3美元(6美元)
总费用是29美元。
我必须执行的特定敲除代码从先前定义的(和有效的) this.wantedShares()绑定中获取20个份额。
代码:
this.totalCost = ko.computed(function(){
var wantedShares = this.wantedShares();
var shareCounter = 0.00;
var counter = 0;
var totalPrice = 0.00;
$.getJSON("sell.json", function(json){
$.each(json, function() {
if(shareCounter <= wantedShares){
shareCounter = shareCounter + json[counter].shares;
totalPrice = totalPrice + (json[counter].price * json[counter].shares);
counter++;
}
});
});
return totalPrice;
}, this);这段代码不工作,不管发生了什么,它根本没有更新totalPrice -它仍然是0。有什么想法吗?
发布于 2012-03-30 07:01:28
AJAX是异步的,因此您的返回将在ajax完成之前触发
发布于 2012-03-30 07:07:13
您的$.getJSON函数是异步的,当它返回时,它会执行您的回调,但在此期间,您已经返回了0的totalPrice。我建议切换到wantedShares上的订阅,并使totalPrice成为您在回调中设置的可观察对象。
发布于 2012-03-30 07:07:50
$.getJSON是一个异步请求。"AJAX“中的”A“=异步。
当Knockout计算出您的计算值时,它不会等待异步操作完成。因此,它将始终返回0。
底线:不要在计算的值内执行AJAX请求。
相反,可以这样做:
// Fetch all the shares asynchronously.
var allShares = ko.observableArray();
$.getJSON("sell.json", function(shares) { allShares(shares); });
// The totalCost observable is dependent on the allShares.
// When allShares changes asynchronously, totalCost will get re-evaluated.
var totalCost = ko.computed(function() {
var shareCounter = 0.00;
var totalPrice = 0.00;
allShares().each(function(share) {
if(shareCounter <= wantedShares().length) {
shareCounter = shareCounter + share.shares;
totalPrice = totalPrice + (share.price * share.shares);
}
});
});我已经创建了演示它工作的this JSFiddle。
https://stackoverflow.com/questions/9934363
复制相似问题