Search code examples
jqueryapiknockout.jsmappinggetjson

Looping through data with Knockout JS and API


I'm having a really tough time getting a sample snippet of code to display data using knockout and a flickr api. My goal is to understand where i'm going wrong. I would be very grateful if someone would mind pointing me in the right direction.

The commented out code within my fiddle does successfully grab JSON data from flickr for my hardcoded search. My issues is how to utilize knockout JS to loop through the data and display the links.

My fiddle: https://jsfiddle.net/jaloomis111/y9qkefLt/

<table>
   <tbody data-bind="foreach: birdList">
       <tr>
            <td><span data-bind="text: link"></span></td>
        </tr>
   </tbody>
</table>

<script>
//test to recieve JSON Data...works
//$.getJSON('https://api.flickr.com/services/feeds/photos_public.gne?tags="birds"&format=json&jsoncallback=?', function(data) { 
//console.log(data)
//})

function bird(data) {
    this.link = ko.observable(data.link);
}

function AppViewModel() {
    var self = this;
    self.birdList = ko.observableArray([]);

    $.getJSON('https://api.flickr.com/services/feeds/photos_public.gne?tags="birds"&format=json&jsoncallback=?', function(data) { 

   var mappedBirds = $.map(data.link, function(item) { return new bird(item) 
   });
   self.birdList(mappedBirds);
   console.log(self.mappedBirds());
 })

 }
 // Activates knockout.js
 ko.applyBindings(new AppViewModel());

 </script>

Solution

  • I think you have it, but you are referencing the wrong thing in your $.map. Change data.link to data.items jsfiddle.net/y9qkefLt/1