Created
May 27, 2013 08:26
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}); | |
}); | |
}); | |
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
In modern jQuery,
can be reduced to:
line 14, I think you meant to write
JSON.parse
instead ofnew 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:Notice that I've been careful to never use indices, thus guaranteeing that the data matched the element it was pulled from.