Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create ko.observableArray from JSON Object in knockout

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

like image 607
Maxali Avatar asked Mar 21 '12 00:03

Maxali


People also ask

What is Ko observableArray?

If you want to detect and respond to changes of a collection of things, use an observableArray . This is useful in many scenarios where you're displaying or editing multiple values and need repeated sections of UI to appear and disappear as items are added and removed.

How do you update items in observableArray knockout?

You should look at defining the object structure for each element of your array and then add elements of that type to your observable array. Once this is done, you will be able to do something like item. productQuantity(20) and the UI will update itself immediately. EDIT Added the function provided by the OP :).

How do I get Knockout JS data?

prototype. loadNote = function (id) { var self = this; $. getJSON(uri + '/' + id, function (data) { self. note(data); }); }; // Apply bindings ko.


1 Answers

Try declaring ( where you have the // Data )

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

then in the load...

self.allEntries(result.feed.entries);
like image 199
Keith Nicholas Avatar answered Oct 05 '22 06:10

Keith Nicholas