Skip to content

Commit ff053e8

Browse files
authored
[examples] Add bespoke JS version of Context Basics (#1233)
1 parent fa3f70a commit ff053e8

File tree

2 files changed

+65
-2
lines changed

2 files changed

+65
-2
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
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);

packages/lit-dev-content/samples/examples/context-basics/elements.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ type ContextValue = string;
1212
// The context object acts as a key. A consumer will only receive
1313
// values from a provider if their contexts match. A Symbol ensures
1414
// that this context will be unique.
15-
const context = createContext<ContextValue>(Symbol());
15+
const context = createContext<ContextValue>(contextKey);
1616

1717
@customElement('provider-el')
1818
export class ProviderEl extends LitElement {
@@ -43,7 +43,7 @@ export class ConsumerEl extends LitElement {
4343
providedData = '';
4444

4545
render() {
46-
return html` <h3>Consumer data: <code>${this.providedData}</code></h3> `;
46+
return html`<h3>Consumer data: <code>${this.providedData}</code></h3>`;
4747
}
4848
}
4949

0 commit comments

Comments
 (0)