[英]Going through a JSON document array in Javascript & JQuery with KnockoutJS
Right now I have the following JSON document: 现在我有以下JSON文档:
[
{
"price":"1.0",
"shares":13
},
{
"price":"2.0",
"shares":5
},
{
"price":"3.0",
"shares":24
}
]
If someone wants 20 shares, I want to return the lowest price possible for 20 shares. 如果有人想要20股,我想要返回20股的最低价格。 In this case its:
在这种情况下,它:
13 shares at $1 ($13) 13股1美元(13美元)
5 shares at $2 ($10) 5股2美元(10美元)
2 shares at $3 ($6) 2股3美元(6美元)
the total cost is $29 总费用是29美元
The specific knockout code I have to do this gets the 20 shares from a previously defined (and working) this.wantedShares() binding. 我必须执行此操作的特定挖掘代码从之前定义的(并且正在工作)this.wantedShares()绑定中获取20个共享。
code: 码:
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);
This code doesn't work, whatever is happening, its not updating totalPrice at all - it remains at 0. Any ideas? 这段代码不起作用,无论发生什么,它根本不更新totalPrice - 它保持为0.任何想法?
AJAX是异步的,所以你的返回将在ajax完成之前触发
你的$ .getJSON函数是异步的,当它返回时它会执行你的回调,但同时你已经返回了totalPrice为0.我建议切换到wantedShares的订阅并使totalPrice成为你在回调中设置的可观察量。
$.getJSON is an asynchronous request. $ .getJSON是一个异步请求。 The 'A' in "AJAX" = asynchronous.
“AJAX”中的“A”=异步。
When Knockout evaluates your computed value, it's not going to wait for the asynchronous operation to complete. 当Knockout评估您的计算值时,它不会等待异步操作完成。 Therefore, it will always return 0.
因此,它将始终返回0。
Bottom line: don't do AJAX requests inside your computed value. 底线:不要在计算值内执行AJAX请求。
Instead, do something like this: 相反,做这样的事情:
// 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);
}
});
});
I've created this JSFiddle that shows it working. 我创建了这个JSFiddle ,显示它正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.