forked from makersacademy/news-summary-challenge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnewsView.js
68 lines (60 loc) · 2.24 KB
/
newsView.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
class NewsView {
constructor(model, client) {
this.model = model;
this.client = client;
this.mainContainerEl = document.querySelector("#main-container");
this.searchButton = document.querySelector("#news-search-button");
this.searchButton.addEventListener("click", () => {
const searchTerm = document.querySelector("#news-search-input").value;
document.querySelector("#news-search-input").value = "";
this.displayTopicArticles(searchTerm);
})
}
displayArticles() {
const existingArticles = document.querySelectorAll(".article");
existingArticles.forEach(story => story.remove());
const articles = this.model.getArticles();
articles.forEach((article) => {
const divEl = document.createElement("div");
divEl.className = "article";
const paraEl = document.createElement("p");
paraEl.textContent = article.fields.headline;
divEl.append(paraEl);
const imageEl = document.createElement("img")
imageEl.src = article.fields.thumbnail;
divEl.append(imageEl);
const linkEl = document.createElement("a");
linkEl.innerHTML = "Read more";
linkEl.href = article.webUrl;
divEl.append(linkEl);
this.mainContainerEl.append(divEl);
})
}
displayArticlesFromApi() {
return this.client.loadArticles()
.then((articles) => {
this.model.reset();
this.model.setArticles(articles);
this.displayArticles();
}).catch(() => this.displayError())
}
displayTopicArticles(topic) {
return this.client.loadTopicArticles(topic)
.then((articles) => {
this.model.reset();
this.model.setArticles(articles);
this.displayArticles();
}).catch(() => this.displayError())
}
displayError() {
const existingArticles = document.querySelectorAll(".article");
existingArticles.forEach(story => story.remove());
const existingErrorMessages = document.querySelectorAll(".error-message");
existingErrorMessages.forEach(message => message.remove())
const errorEl = document.createElement("div");
errorEl.textContent = "Oopsy daisy, something's gone amiss!";
errorEl.className = "error-message";
this.mainContainerEl.append(errorEl)
}
}
module.exports = NewsView;