Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialLeonardo Cavalcanti
5,308 PointsgenerateHTML is called without passing any parameters but it has "data" for a parameter, how is the data being passed in
The function generateHTML has (data) for a parameter, but on line 44 it is being called as a callback inside the method getJSON without any parameters, how then is it functioning normally? In other words, how is the function generateHTML receiving its data for its generating the HTML without anything being given to it?
const astrosUrl = 'http://api.open-notify.org/astros.json';
const wikiUrl = 'https://en.wikipedia.org/api/rest_v1/page/summary/';
const peopleList = document.getElementById('people');
const btn = document.querySelector('button');
// Make an AJAX request
function getJSON(url, callback) {
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = () => {
if(xhr.status === 200) {
let data = JSON.parse(xhr.responseText);
return callback(data);
}
};
xhr.send();
}
// Generate the markup for each profile
function generateHTML(data) {
const section = document.createElement('section');
peopleList.appendChild(section);
// Check if request returns a 'standard' page from Wiki
if (data.type === 'standard') {
section.innerHTML = `
<img src=${data.thumbnail.source}>
<h2>${data.title}</h2>
<p>${data.description}</p>
<p>${data.extract}</p>
`;
} else {
section.innerHTML = `
<img src="img/profile.jpg" alt="ocean clouds seen from space">
<h2>${data.title}</h2>
<p>Results unavailable for ${data.title}</p>
${data.extract_html}
`;
}
}
btn.addEventListener('click', (event) =>
getJSON(astrosUrl, (data) => {
data.people.map(person => {
getJSON(wikiUrl + person.name, generateHTML);
});
event.target.remove();
}));
1 Answer
Steven Parker
231,269 PointsThe callback is being passed as an argument here, it is not being called (yet).
When it does get called from inside of the getJSON code (on line 13), it will be given the argument it needs.
Leonardo Cavalcanti
5,308 PointsLeonardo Cavalcanti
5,308 PointsSo the "return callback(data);" is invoked so the parameter "data" here becomes the parameter for generateHTML(data) ?
Steven Parker
231,269 PointsSteven Parker
231,269 PointsThat's it!