Create ko.observableArray from JSON Object in knockout
Asked Answered
W

1

5

I just started using knockout.js and it works great with normal bidings. I have a problem with 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

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

<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.

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

Washing answered 21/3, 2012 at 0:40 Comment(1)
pretty sure you need to create the array upfront, then in your load you fill in that array......Eaves
E
23

Try declaring ( where you have the // Data )

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

then in the load...

self.allEntries(result.feed.entries);
Eaves answered 21/3, 2012 at 0:55 Comment(4)
Hey Maxali, is it possible for you to put everything working in JSFIDDLE? I really like to see a working example of the feed being rendered. It might prove to be helpful for me. ThanksObedient
+1 for solution. Surprised that this answer hasn't already had 10's of votes up as it is one of these questions/answers which loads of people are going to ask when using Knockout! :DBuroker
you can end up coming at these things from different angles in knockout, a lot of the SO questions are very similar in nature but just slightly different scenariousEaves
It may be worth noting that using the KO mapping plugin (knockoutjs.com/documentation/plugins-mapping.html) might be a better option (in case you have several properties to set).Gladisgladney

© 2022 - 2024 — McMap. All rights reserved.