Pregunta

I'm currently experimenting with Knockout JS just to get the hang of the library and all of it's capabilities and I appear to have run into a wall with handling external JSON data.

In the Codepen below I have a dummy observable array which is working fine. Commented out below that is the actual JSON data I want to experiment with. It takes an external feed using $.GETJSON and maps that to filter the results to extract only the data I want to use in my HTML template.

My problem is that I can't seem to get the external JSON to bind to the HTML as I always get 'tracks' is not defined, or sometimes even an empty console (which is always helpful).

Can anybody point me in the right direction of how to handle external JSON? I've done searching around and I can't see much info dedicated to handling external JSON.

http://codepen.io/anon/pen/Hnamf

¿Fue útil?

Solución

Looking at your codepen, it isn't entirely clear how you want this to work, but it certainly can be made to work. Just as a quick demo, I moved your $.getJSON inside your init function so that it can actually have access to the view model and then in the callback set what you are getting to the property self.tracks. Since you were binding "tracks", I changed "title" to "tracks", but you can obviously do whatever makes sense to you:

 $.getJSON('http://api.soundcloud.com/users/guy-j/tracks.json?client_id=YOUR_CLIENT_ID', {limit: 200}, function(data) {
       vm.tracks($.map(data, function (track) {
             return {
                   artwork: track.artwork_url,
                   duration: track.duration,
                   permalink: track.permalink_url,
                   listens: track.playback_count,
                   stream: track.stream_url,
                   track: track.title
             };
        }));
  });

http://codepen.io/anon/pen/HAkhy

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top