Created
October 16, 2020 15:00
-
-
Save fantonangeli/16ba060f90f49a0266acf8f30625cdfe to your computer and use it in GitHub Desktop.
This file contains 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
'use strict'; | |
//SETTINGS | |
const commentsServiceUrl="https://www.example.com/comments"; | |
/** | |
* remove html from a text | |
* | |
* @param {string} text the text to clean | |
*/ | |
function removeHTML(text){ | |
if(!text) return ""; | |
return jQuery('<i>'+text+'</i>').text(); | |
} | |
/** | |
* get the html of a single comment | |
* | |
* @param {object} commentData the data of the comment | |
* @return {string} the html | |
*/ | |
function getHTMLSingleComment(commentData){ | |
let message=""; | |
if(!commentData) return ""; | |
message=removeHTML(commentData.message); | |
return `<div class="comment-item"> <div class="comment-item__username">${commentData.username}</div> <div class="comment-item__message">${message}</div> </div>`; | |
} | |
/** | |
* fetchData. | |
* | |
* @param {} dataCount | |
*/ | |
async function fetchData(dataCount){ | |
let data; | |
// return [{ | |
// "id": 123, | |
// "username": "User 1", | |
// "message": "Cool product!" | |
// }, { | |
// "id": 456, | |
// "username": "User 2", | |
// "message": "Didn't like it that much" | |
// }]; | |
data=await jQuery.get(commentsServiceUrl, {count:dataCount}); | |
return data; | |
} | |
/** | |
* loads the html of all the comments | |
* | |
* @param {string} dataCount | |
* @return {string} the html | |
*/ | |
async function getHTMLComments(dataCount){ | |
let data; | |
let html=""; | |
data=await fetchData(dataCount); | |
if(!data) return ""; | |
for (var i = 0, len = data.length; i < len; i++) { | |
html+=getHTMLSingleComment(data[i]); | |
} | |
return html; | |
} | |
/** | |
* show comments in a comment-list element | |
* | |
* @param {node} commentList | |
*/ | |
async function showComments(commentList){ | |
let dataCount=0; | |
let el,html; | |
if(!commentList) return; | |
el=jQuery(commentList); | |
el.html("Loading..."); | |
dataCount=el.data('count'); | |
html=await getHTMLComments(dataCount); | |
el.html(html+""); | |
} | |
function solution() { | |
jQuery('.comment-list').each(function(){ | |
showComments(this); | |
}); | |
} | |
// $(function(){ | |
// solution(); | |
// }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment