Skip to content

Instantly share code, notes, and snippets.

@edouard-lopez
Created May 27, 2013 08:26
Show Gist options
  • Save edouard-lopez/5655842 to your computer and use it in GitHub Desktop.
Save edouard-lopez/5655842 to your computer and use it in GitHub Desktop.
Fetch JSON data for each <div class="cheatsheet" data-json="data/wiki.json"></div> element
var $, Handlebars; // sublime-text-2
$(document).ready(function () {
'use strict';
var jxhr = [];
var csData = [];
var sheetList = $('.cheatsheet');
sheetList.each(function () {
var url = $(this).data('json');
jxhr.push(
$.getJSON(url, function (json) {
csData.push(new Object(json));
})
);
});
$.when.apply($, jxhr).done(function() {
$.each(sheetList, function(i, sheet) {
var compiledTemplate = Handlebars.templates['cheatsheet.hbs'];
var tpl = compiledTemplate(csData[i]);
$(sheet).html(tpl);
});
});
});
@DavidBruant
Copy link

In modern jQuery,

$(document).ready(function () {
  ...
})

can be reduced to:

$(function () {
  ...
})

line 14, I think you meant to write JSON.parse instead of new Object

The order in which csData.push (line 14) is called depends on the order HTTP requests come back. This will not work really well with what you do line 22 (where you seem to assume that the index in sheetList matches the index in csData).

For the rest, from what I understand, you want to populate .cheatsheet elements with the content fetched from their data-json attribute. If I understand well, it can be reduced to:

$(function(){
   var compiledTemplate = Handlebars.templates['cheatsheet.hbs'];

  $('.cheatsheet').each(function(i, sheet){
    var url = $(sheet).data('json');
    $.getJSON(url).then(function (json) {
      var tpl = compiledTemplate( JSON.parse(json) );
      $(sheet).html(tpl);
    })
  })
})

Notice that I've been careful to never use indices, thus guaranteeing that the data matched the element it was pulled from.

@edouard-lopez
Copy link
Author

Thanks, a lot simpler than what I did. I was missing the deferred.then() method.
The JSON.parse was thorwing an error (JSON.parse: unexpected character) as I request a JSON file already.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment