Skip to content

Commit ee0ced0

Browse files
committed
class17 live coding
1 parent 6b509bb commit ee0ced0

6 files changed

Lines changed: 1017 additions & 0 deletions

File tree

src/live/app.js

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
'use strict';
2+
{
3+
// cb(err, data)
4+
5+
function createAndAppend(name, parent, options = {}) {
6+
const elem = document.createElement(name);
7+
parent.appendChild(elem);
8+
for (const key of Object.keys(options)) {
9+
if (key === 'text') {
10+
elem.innerText = options.text;
11+
} else {
12+
elem.setAttribute(key, options[key]);
13+
}
14+
}
15+
return elem;
16+
}
17+
18+
function addRow(label, value, tbody) {
19+
const tr = createAndAppend('tr', tbody);
20+
createAndAppend('td', tr, { class: 'label', text: label });
21+
createAndAppend('td', tr, { text: value });
22+
}
23+
24+
function renderLaureates(ul, data) {
25+
ul.innerHTML = '';
26+
27+
data.laureates.forEach(laureate => {
28+
const li = createAndAppend('li', ul, { class: 'list-item' });
29+
const table = createAndAppend('table', li);
30+
const tbody = createAndAppend('tbody', table);
31+
const fullName = `${laureate.firstname} ${laureate.surname}`;
32+
addRow('Name:', fullName, tbody);
33+
const bornDetails = `${laureate.born}, ${laureate.bornCity}`;
34+
addRow('Born:', bornDetails, tbody);
35+
});
36+
}
37+
38+
function main() {
39+
const queries = [
40+
{
41+
description: 'All Dutch lauerates',
42+
url: 'http://api.nobelprize.org/v1/laureate.json?bornCountryCode=NL'
43+
},
44+
{
45+
description: 'All female laureates',
46+
url: 'http://api.nobelprize.org/v1/laureate.json?gender=female'
47+
}
48+
];
49+
50+
const root = document.getElementById('root');
51+
const select = createAndAppend('select', root);
52+
queries.forEach((query, index) => {
53+
createAndAppend('option', select, { value: index, text: query.description });
54+
});
55+
56+
const ul = createAndAppend('ul', root, { id: 'list-container' });
57+
58+
select.addEventListener('change', () => {
59+
console.log(select.value);
60+
const query = queries[select.value];
61+
fetchJSON(query.url, (err, data) => {
62+
renderLaureates(ul, data);
63+
});
64+
});
65+
66+
67+
fetchJSON(queries[0].url, (err, data) => {
68+
renderLaureates(ul, data);
69+
});
70+
71+
}
72+
73+
window.onload = main;
74+
}

src/live/fetchjson.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
'use strict';
2+
3+
function fetchJSON(url, cb) {
4+
const xhr = new XMLHttpRequest();
5+
xhr.open('GET', url);
6+
xhr.responseType = 'json';
7+
xhr.onload = () => {
8+
if (xhr.status < 400) {
9+
cb(null, xhr.response);
10+
} else {
11+
cb(new Error(`Network error: ${xhr.status} - ${xhr.statusText}`));
12+
}
13+
};
14+
xhr.onerror = () => cb(new Error('Network request failed'));
15+
xhr.send();
16+
}
17+

0 commit comments

Comments
 (0)