javascript 在淘汰赛中从 JSON 对象创建 ko.observableArray

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9797096/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 07:53:06  来源:igfitidea点击:

Create ko.observableArray from JSON Object in knockout

javascriptjsonknockout.jsgoogle-feed-api

提问by Maxali

I just started using knockout.js and it works great with normal bidings. I have a problem with observableArray.

我刚开始使用knockout.js,它在正常投标中效果很好。我对 observableArray 有问题。

I want to create an observableArray and assign to it a JSON data from Google Feed API. Here is the JSON format https://developers.google.com/feed/v1/devguide#resultJson

我想创建一个 observableArray 并将来自 Google Feed API 的 JSON 数据分配给它。这是 JSON 格式https://developers.google.com/feed/v1/devguide#resultJson

google.load("feeds", "1");  // Loads Google Feed API
function FeedViewModel()
{
    // Data
    var self = this;
    self.allEntries = null;

    // Example property, and it works
    self.feedHead = ko.observable("BBC News");

    var feed = new google.feeds.Feed("feeds.feedburner.com/BBCNews");
    feed.setResultFormat(google.feeds.Feed.JSON_FORMAT);
    feed.includeHistoricalEntries();
    feed.setNumEntries(30);

    // Loads feed results
    feed.load(function (result) {
        if (!result.error) {           
            self.allEntries = ko.observableArray(result.feed.entries);

            // accessing the title from here is OK
            alert(self.allEntries()[1].title);
        }        
    });
}

In the above example, accessing the array from the ViewModel is OK but I need to display it in the view (to the browser) using foreach:allEntries

在上面的例子中,从 ViewModel 访问数组是可以的,但我需要使用 foreach:allEntries 在视图中显示它(到浏览器)

<h2 data-bind="text: feedHead">Latest News</h2>
<!-- ko foreach:allEntries -->
    <div class="lists">
        <a href="#" data-bind="text: title"></a>
    </div>
<!-- /ko -->

But nothing the ko foreach loop returns nothing. The observable feedHead is OK.

但是 ko foreach 循环什么都不返回。可观察的 feedHead 没问题。

Also I dont have any JS error. Any help..

我也没有任何 JS 错误。任何帮助..

回答by Keith Nicholas

Try declaring ( where you have the // Data )

尝试声明(您拥有 // Data 的位置)

self.allEntries = ko.observableArray([]);

then in the load...

然后在负载...

self.allEntries(result.feed.entries);