forked from LarsDenBakker/lit-html-workshop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
8-polymer-components.html
121 lines (105 loc) · 3.15 KB
/
8-polymer-components.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
<!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';
import 'https://unpkg.com/@polymer/paper-button/paper-button.js?module';
class MyElement extends LitElement {
static get styles() {
return css`
:host {
display: block;
}
`;
}
static get properties() {
return {
articles: { type: Array },
filter: { type: String }
};
}
constructor() {
super();
this.articles = [];
// add a filter
this.filter = 'all';
}
connectedCallback() {
super.connectedCallback();
fetch('https://newsapi.org/v2/everything?q=tech&apiKey=<your-api-key>')
.then(response => response.json())
.then(response => {
this.articles = response.articles.map((article, i) => ({...article, id: i, read: false}));
})
}
_toggleReadStatus(e) {
this.articles[e.detail].read = !this.articles[e.detail].read;
this.requestUpdate();
}
render() {
const filteredArticles = this.articles.filter(article => {
if(this.filter === 'read') return article.read;
if(this.filter === 'unread') return !article.read;
if(this.filter === 'all') return true;
});
return html`
<paper-button raised @click=${() => this.filter = 'all'}>all</paper-button>
<paper-button raised @click=${() => this.filter = 'read'}>read</paper-button>
<paper-button raised @click=${() => this.filter = 'unread'}>unread</paper-button>
<ul>
<!-- apply filter to the array -->
${filteredArticles.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 styles() {
return css`
:host {
display: block;
}
`;
}
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>
<paper-button @click=${this._toggleRead}>
${this.read ? 'read' : 'unread'}
</paper-button>
<h2>${this.title}</h2>
<p>${this.description}</p>
</li>
`;
}
}
customElements.define('my-article', MyArticle);
</script>
</head>
<body>
<my-element></my-element>
</body>
</html>