var timeLine = document.querySelector('.timeLine'); var totalTweets = []; /** * get * * Tiny utility for making XHR requests * @param {String} url * @param {Function} callback [description] */ function get(url, callback, errback) { var req = new XMLHttpRequest(); req.open('GET', url, true); req.onreadystatechange = function() { if(req.readyState != 4) return; if (req.status === 200) { callback(req); } else { errback(req); } }; req.send(null); } /** * Asynch Requests * Nest callback grossness */ // our first async req get('https://api.myjson.com/bins/2qjdn', function(data){ totalTweets.push(data.response); // our second async req wrapped in a 2 second delay setTimeout(function(){ get('https://api.myjson.com/bins/3zjqz', function(data){ totalTweets.push(data.response); // our third async req get('https://api.myjson.com/bins/29e3f', function(data){ totalTweets.push(data.response); showStats(); }, function(err){ onError(err); } ); }, function(err){ onError(err); } ); }, 2000); }, function(err){ onError(err); } ); /** * showStats * * Populate some stats */ function showStats(){ var totalTweets = document.querySelector('.totalTweets'); totalTweets.textContent = countProperties('user') || 0; var totalPhotos = document.querySelector('.totalPhotos'); totalPhotos.textContent = countProperties('photo') || 0; var totalFavourites = document.querySelector('.totalFavourites'); totalFavourites.textContent = countProperties('favourited') || 0; showTimeline(); } /** * showTimeline * * Flesh out some sweet sweet tweet data * then append to the .timeLine */ function showTimeline(){ var el = document.createElement('div'); totalTweets.forEach(function(tweet){ tweet = JSON.parse(tweet); var tweetElement = el.cloneNode(true); tweetElement.classList.add('tweet'); var name = el.cloneNode(true); name.classList.add('tweet__name'); name.textContent = tweet.user.name; var handle = el.cloneNode(true); handle.classList.add('tweet__handle'); handle.textContent = '@' + tweet.user.handle; var message = el.cloneNode(true); message.classList.add('tweet__message'); message.textContent = tweet.message; tweetElement.appendChild(name); tweetElement.appendChild(handle); tweetElement.appendChild(message); timeLine.appendChild(tweetElement); }); } /** * OnError * * @param {error} err */ function onError (err) { console.error("Error: err"); } /** * countProperties * * Utility function to help us count certain props * * @param {String} a specific prop * @return {Number} count */ function countProperties(prop) { var count = 0; totalTweets.forEach(function(tweet){ tweet = JSON.parse(tweet) if (prop in tweet) count++; }); return count; }