Search code examples
javascriptjsonajaxloopshandlebars.js

Show values from multiple json objects using handlebars.js


I'm trying to show data from two separate ajax calls.

I've started experimenting with handlebars.js and managed to show data but only from one call. How can I refactor my code to show data from the second call as well?

HTML:

<header>
  <img id="twitch-logo" src="https://upload.wikimedia.org/wikipedia/commons/c/c6/Twitch_logo_%28wordmark_only%29.svg">
</header>

<div id="result-placeholder"></div>
<script type="text/handlebars-template" id="handlebars-template"> 
  {{#each this}}
  <div class="result-wrapper">
    <a href="{{channel.url}}" target="_blank">
      <div><img src="{{channel.logo}}" class="result-logo"></div>
      <div class="result-name">User: {{channel.display_name}}</div>
      <div class="result-game">Currently streaming: {{channel.game}}</div>
    </a>
  </div>
  {{/each}}
</script>

JS:

var streamers = ['monstercat', 'lirik'];

function getStream(name) {
  return $.ajax('https://api.twitch.tv/kraken/streams/' + name + '?callback=?', { dataType: 'JSON' });
}

function displayStream(data) {
  var $placeHolder = $("#result-placeholder");
  var handlebarsTemplate = $("#handlebars-template").html();
  var templateCompile = Handlebars.compile(handlebarsTemplate);
  $placeHolder.html(templateCompile(data)); 
}

streamers.map(function(element) {
  getStream(element)
    .then(displayStream);
});

Solution

  • it looks like you are using jQuery to perform the http fetch of your streams. I suggest looking at the jQuery API, and use for instance jQuery.when( deferreds ) to combine async fetch of 2 or more resources:

    https://api.jquery.com/jquery.when/