Skip to content

Commit

Permalink
[examples] Add bespoke JS version of Context Basics (#1233)
Browse files Browse the repository at this point in the history
  • Loading branch information
augustjk authored Oct 20, 2023
1 parent fa3f70a commit ff053e8
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -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`
<h3>Provider's data: <code>${this.data}</code></h3>
<slot></slot>
`;
}
}
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`<h3>Consumer data: <code>${this.providedData}</code></h3>`;
}
}
customElements.define('consumer-el', ConsumerEl);
Original file line number Diff line number Diff line change
Expand Up @@ -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<ContextValue>(Symbol());
const context = createContext<ContextValue>(contextKey);

@customElement('provider-el')
export class ProviderEl extends LitElement {
Expand Down Expand Up @@ -43,7 +43,7 @@ export class ConsumerEl extends LitElement {
providedData = '';

render() {
return html` <h3>Consumer data: <code>${this.providedData}</code></h3> `;
return html`<h3>Consumer data: <code>${this.providedData}</code></h3>`;
}
}

Expand Down

0 comments on commit ff053e8

Please sign in to comment.