diff --git a/packages/lit-dev-content/samples/examples/context-basics/elements.js b/packages/lit-dev-content/samples/examples/context-basics/elements.js new file mode 100644 index 000000000..d7a1eb91e --- /dev/null +++ b/packages/lit-dev-content/samples/examples/context-basics/elements.js @@ -0,0 +1,63 @@ +import {html, LitElement} from 'lit'; +import {ContextProvider, ContextConsumer, createContext} from '@lit/context'; + +import {providerStyles} from './styles.js'; + +const contextKey = Symbol('contextKey'); + +// Context object, which acts like a key for the context. +// The context object acts as a key. A consumer will only receive +// values from a provider if their contexts match. A Symbol ensures +// that this context will be unique. +const context = createContext(contextKey); + +export class ProviderEl extends LitElement { + static styles = providerStyles; + + static properties = { + data: {}, + }; + + constructor() { + super(); + this._provider = new ContextProvider(this, {context}); + this.data = 'Initial'; + } + + /** + * `data` will be provided to any consumer that is in the DOM tree below it. + */ + set data(value) { + this._data = value; + this._provider.setValue(value); + } + + get data() { + return this._data; + } + + render() { + return html` +

Provider's data: ${this.data}

+ + `; + } +} +customElements.define('provider-el', ProviderEl); + +export class ConsumerEl extends LitElement { + _consumer = new ContextConsumer(this, {context}); + + /** + * `providedData` will be populated by the first ancestor element which + * provides a value for `context`. + */ + get providedData() { + return this._consumer.value; + } + + render() { + return html`

Consumer data: ${this.providedData}

`; + } +} +customElements.define('consumer-el', ConsumerEl); diff --git a/packages/lit-dev-content/samples/examples/context-basics/elements.ts b/packages/lit-dev-content/samples/examples/context-basics/elements.ts index b188f5b92..1c7d56811 100644 --- a/packages/lit-dev-content/samples/examples/context-basics/elements.ts +++ b/packages/lit-dev-content/samples/examples/context-basics/elements.ts @@ -12,7 +12,7 @@ type ContextValue = string; // The context object acts as a key. A consumer will only receive // values from a provider if their contexts match. A Symbol ensures // that this context will be unique. -const context = createContext(Symbol()); +const context = createContext(contextKey); @customElement('provider-el') export class ProviderEl extends LitElement { @@ -43,7 +43,7 @@ export class ConsumerEl extends LitElement { providedData = ''; render() { - return html`

Consumer data: ${this.providedData}

`; + return html`

Consumer data: ${this.providedData}

`; } }