|
| 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 | +} |
0 commit comments