0

I am new to javascript promises before diving deep, I want to know whether are they required in this scenario or not.

I am making an ajax request to get data and creating DOM elements on response (news widget). I have a search input, where I can filter the titles and content of news. So after the list of news is loaded in DOM, on Keyup event i can filter the content and titles of news.

I know I can wrap the ajax request inside the keyup callback and request filtered data, but I do not know how to go about when the data in DOM is already loaded.

var xhr = new XMLHttpRequest();

xhr.open("GET", "data.json");
xhr.onreadystatechange = function() {
  if (this.status === 200 && this.readyState === 4) {
    var respneseParse = JSON.parse(this.responseText);
    var articles = respneseParse.results;

    var articleList = '<ul>';
    articles.forEach(function(article,index){
      var relatedStories = article.relatedStories;
      articleList += '<li id="article" onclick= "basanti('+index+')">';
      articleList += '<input type="checkbox" name="article-heading"  id="article-heading'+index+'"><label for="article-heading'+index+'">'+ article.titleNoFormatting +'</label>';
      articleList += '<div id="article-detail'+index+'" style="display:none">';
      articleList += '<img src="'+article.image.url+'" alt="'+ article.titleNoFormatting +'" style="height:'+article.image.tbHeight+';width:'+article.image.tbWidth+';" />';
      articleList += '<p>'+ article.content+'</p>';
      articleList += '<a href="'+article.unescapedUrl+'"> Read more.. </a>';
      if(relatedStories){
        relatedStories.forEach(function(articleRelatedStories){
          articleList += '<ul id="related-stories">';
          articleList += '<li><a href="'+articleRelatedStories.unescapedUrl+'">'+articleRelatedStories.titleNoFormatting+'</a></li>';
          articleList += '</ul>';
        });
      };
      articleList += '</div>';
      articleList += '</li>';
    })
    articleList += '</ul>';

    document.getElementById('article-list').innerHTML = articleList;
  }
};

xhr.send();

var basanti = function (index){
  var articleDetail = document.getElementById('article-detail'+index+'');
  var articleHeading = document.getElementById('article-heading'+index+'');
  if(articleHeading.checked){
    articleDetail.style.display = 'block';
  }else {
    articleDetail.style.display = 'none';
  }

}
Haris Khan
  • 161
  • 2
  • 10
  • have a look at this http://stackoverflow.com/questions/9899372/pure-javascript-equivalent-to-jquerys-ready-how-to-call-a-function-when-the – codenathan Apr 16 '16 at 08:45
  • Promises are very useful, but will not make a difference in this specific problem. If you're just trying to know when the DOM has finished loading, then see the link that codenathan has in the previous comment. – jfriend00 Apr 16 '16 at 16:36

0 Answers0