Create ko.observableArray from JSON object in knockout

I just started using knockout.js and it works great with regular bets. I have a problem with an observable array.

I want to create an observable array and assign it the JSON data from the 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 fine, but I need to display it in the view (in 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 the ko foreach loop does nothing. Observed feed channel in order.

Also I have no JS error. Any help ..

+6
source share
1 answer

Try declaring (where you have // ​​Data)

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

then in the load ...

 self.allEntries(result.feed.entries); 
+22
source

Source: https://habr.com/ru/post/911253/


All Articles