|
| 1 | +import {html, LitElement} from 'lit'; |
| 2 | +import {ContextProvider, ContextConsumer, createContext} from '@lit/context'; |
| 3 | + |
| 4 | +import {providerStyles} from './styles.js'; |
| 5 | + |
| 6 | +const contextKey = Symbol('contextKey'); |
| 7 | + |
| 8 | +// Context object, which acts like a key for the context. |
| 9 | +// The context object acts as a key. A consumer will only receive |
| 10 | +// values from a provider if their contexts match. A Symbol ensures |
| 11 | +// that this context will be unique. |
| 12 | +const context = createContext(contextKey); |
| 13 | + |
| 14 | +export class ProviderEl extends LitElement { |
| 15 | + static styles = providerStyles; |
| 16 | + |
| 17 | + static properties = { |
| 18 | + data: {}, |
| 19 | + }; |
| 20 | + |
| 21 | + constructor() { |
| 22 | + super(); |
| 23 | + this._provider = new ContextProvider(this, {context}); |
| 24 | + this.data = 'Initial'; |
| 25 | + } |
| 26 | + |
| 27 | + /** |
| 28 | + * `data` will be provided to any consumer that is in the DOM tree below it. |
| 29 | + */ |
| 30 | + set data(value) { |
| 31 | + this._data = value; |
| 32 | + this._provider.setValue(value); |
| 33 | + } |
| 34 | + |
| 35 | + get data() { |
| 36 | + return this._data; |
| 37 | + } |
| 38 | + |
| 39 | + render() { |
| 40 | + return html` |
| 41 | + <h3>Provider's data: <code>${this.data}</code></h3> |
| 42 | + <slot></slot> |
| 43 | + `; |
| 44 | + } |
| 45 | +} |
| 46 | +customElements.define('provider-el', ProviderEl); |
| 47 | + |
| 48 | +export class ConsumerEl extends LitElement { |
| 49 | + _consumer = new ContextConsumer(this, {context}); |
| 50 | + |
| 51 | + /** |
| 52 | + * `providedData` will be populated by the first ancestor element which |
| 53 | + * provides a value for `context`. |
| 54 | + */ |
| 55 | + get providedData() { |
| 56 | + return this._consumer.value; |
| 57 | + } |
| 58 | + |
| 59 | + render() { |
| 60 | + return html`<h3>Consumer data: <code>${this.providedData}</code></h3>`; |
| 61 | + } |
| 62 | +} |
| 63 | +customElements.define('consumer-el', ConsumerEl); |
0 commit comments