forked from LarsDenBakker/lit-html-workshop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path5-read-toggle.html
93 lines (80 loc) · 2.34 KB
/
5-read-toggle.html
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<script type="module">
import {LitElement, html, css} from 'https://unpkg.com/[email protected]?module';
class MyElement extends LitElement {
static get properties() {
return {
articles: { type: Array }
};
}
constructor() {
super();
this.articles = [];
}
connectedCallback() {
super.connectedCallback();
fetch('https://newsapi.org/v2/everything?q=tech&apiKey=<your-api-key>')
.then(response => response.json())
.then(response => {
// we'll need to keep track of some kind of id and read status per article
this.articles = response.articles.map((article, i) => ({...article, id: i, read: false}));
});
}
_toggleReadStatus(e) {
this.articles[e.detail].read = !this.articles[e.detail].read;
// when mutating an objects properties, you have to manually call:
this.requestUpdate();
}
render() {
return html`
<ul>
${this.articles.map(article => html`
<my-article
.title=${article.title}
.description=${article.description}
.read=${article.read}
.id=${article.id}
@toggled=${this._toggleReadStatus}
></my-article>
`)}
</ul>
`;
}
}
customElements.define('my-element', MyElement);
class MyArticle extends LitElement {
static get properties() {
return {
title: { type: String },
description: { type: String },
read: { type: Boolean },
id: { type: Number }
}
}
// dispatch an event to the parent element
_toggleRead() {
this.dispatchEvent(new CustomEvent('toggled', { detail: this.id }));
}
render() {
return html`
<li>
<button @click=${this._toggleRead}>
${this.read ? 'read' : 'unread'}
</button>
<h2>${this.title}</h2>
<p>${this.description}</p>
</li>
`;
}
}
customElements.define('my-article', MyArticle);
</script>
</head>
<body>
<my-element></my-element>
</body>
</html>