-
Notifications
You must be signed in to change notification settings - Fork 8
/
context-consumer.js
39 lines (32 loc) · 920 Bytes
/
context-consumer.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
import { observeContext, unobserveContext } from './core.js'
class ContextUpdateEvent extends Event {
constructor(context, value) {
super('context-update', { bubbles: true })
this.context = context
this.value = value
}
}
function setValueDispatchEvent(consumer, value, context) {
consumer.value = value
consumer.dispatchEvent(new ContextUpdateEvent(context, value))
}
class ContextConsumer extends HTMLElement {
static get observedAttributes() {
return ['context']
}
attributeChangedCallback(name, oldValue, value) {
this[name] = value
}
connectedCallback() {
this._context = this.context
if (this._context) {
observeContext(this, this._context, this._context, setValueDispatchEvent)
}
}
disconnectedCallback() {
if (this._context) {
unobserveContext(this, this._context)
}
}
}
customElements.define('context-consumer', ContextConsumer)