首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用KnockoutJS在Javascript和JQuery中遍历JSON文档数组

使用KnockoutJS在Javascript和JQuery中遍历JSON文档数组
EN

Stack Overflow用户
提问于 2012-03-30 06:16:17
回答 3查看 147关注 0票数 1

现在我有以下JSON文档:

代码语言:javascript
复制
[
   {
      "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个份额。

代码:

代码语言:javascript
复制
    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。有什么想法吗?

EN

回答 3

Stack Overflow用户

发布于 2012-03-30 07:01:28

AJAX是异步的,因此您的返回将在ajax完成之前触发

票数 1
EN

Stack Overflow用户

发布于 2012-03-30 07:07:13

您的$.getJSON函数是异步的,当它返回时,它会执行您的回调,但在此期间,您已经返回了0的totalPrice。我建议切换到wantedShares上的订阅,并使totalPrice成为您在回调中设置的可观察对象。

票数 1
EN

Stack Overflow用户

发布于 2012-03-30 07:07:50

$.getJSON是一个异步请求。"AJAX“中的”A“=异步。

当Knockout计算出您的计算值时,它不会等待异步操作完成。因此,它将始终返回0。

底线:不要在计算的值内执行AJAX请求。

相反,可以这样做:

代码语言:javascript
复制
// 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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9934363

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档