Skip to content

Commit 9d4c068

Browse files
Luuk PetersLuuk Peters
authored andcommitted
Enhance documentation on consuming contexts in the Context API with detailed examples and improved clarity
1 parent 8ac996b commit 9d4c068

File tree

1 file changed

+108
-3
lines changed

1 file changed

+108
-3
lines changed

16/umbraco-cms/customizing/foundation/context-api/consume-a-context.md

Lines changed: 108 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,115 @@ New structure:
1818

1919
# Consume a Context
2020
#TODO# - Introduction
21-
There are different ways to consume a Context API. The most straightforward implementation is done on an Umbraco Element with a Context Token, but there are alternative methods.
21+
There are two ways to consume a context: get a __one-time reference__ to the context, or get a __subscription__ for handling context changes. The Context API is a flexible system where contexts can get disonnected or replaced. A subscription allows for the handling of these changes. However, subscriptions use more resources and are typically consumed in the constructor, a time when the computer is already processing a lot. Which way to go depends on your use case. However, in all cases the following applies.
2222

23-
## Consume context in an Umbraco element
24-
Most extensions derive from an [Umbraco Element](../umbraco-element/) that provides a lot of helper functions. These include helpers for consuming a context. You only need to provide the key to the context.
23+
If you need a context from the moment your element loads and you hold on to the context by putting it into a variable, you should always use the subscription. Otherwise you risk holding on to a context that could be disconnected or replaced without you knowing. Also if you're observing properties of a context, you want know if the context is still available and a subscription also makes the best sense.
24+
25+
A one-time reference is great for fire-and-forget events in your element. Those include events that occur after for instance user interaction. The key here is that the context is not needed when the element is initialized, but only needed then a specific criteria is met. We just need to get a context to do something, but after that, there is no reason to keep the context.
26+
27+
## Consume context in an element
28+
The most straightforward way to consume a context is on an Umbraco Element with a Context Token. Most extensions derive from an [Umbraco Element](../umbraco-element/) that provides a lot of helper functions. These include helpers for getting and consuming a context. You only need to provide the key to the context.
29+
30+
### Get a one-time reference to a context
31+
A one-time reference to a context is for when you want to perform some action and then forget the context. A good example of this is when you want to display a notification in the backoffice when a user performs an action.
32+
33+
{% tabs %}
34+
{% tab title="Lit element (typescript)" %}
35+
```typescript
36+
import { UMB_NOTIFICATION_CONTEXT } from '@umbraco-cms/backoffice/notification';
37+
import { html } from '@umbraco-cms/backoffice/external/lit';
38+
import { UmbLitElement } from '@umbraco-cms/backoffice/lit-element';
39+
40+
//The example element extends the UmbLitElement (which is the same as UmbElementMixin(LitElement))
41+
//This gives us all the helpers we need to get or consume contexts
42+
export default class ExampleElement extends UmbLitElement {
43+
44+
/**
45+
* Notification handler for the notification button
46+
* @param {Event} event The event that triggered the change
47+
*/
48+
async #notificationButtonClick(event: Event) {
49+
//We try to get an instance of the context
50+
const notificationContext = await this.getContext(UMB_NOTIFICATION_CONTEXT);
51+
if (!notificationContext) {
52+
throw new Error('Notification context not found!');
53+
}
54+
55+
notificationContext?.peek("positive", {
56+
data: {
57+
headline: "Success",
58+
message: "The notification button was clicked successfully!"
59+
}
60+
});
61+
62+
//The notification is sent, now forget the context
63+
}
64+
65+
/**
66+
* Renders the lit component
67+
* @see https://lit.dev/docs/components/rendering/
68+
*/
69+
render() {
70+
return html`
71+
<uui-button look="primary" color="default" @click="${this.#notificationButtonClick}">
72+
Click me for a notification!
73+
</uui-button>
74+
`;
75+
}
76+
}
77+
78+
// Register the custom element
79+
customElements.define('example-element', ExampleElement);
80+
```
81+
{% endtab %}
82+
{% tab title="HTML element (typescript)" %}
83+
```typescript
84+
import { UMB_NOTIFICATION_CONTEXT } from '@umbraco-cms/backoffice/notification';
85+
import { UmbElementMixin } from '@umbraco-cms/backoffice/element-api';
86+
87+
// The example element extends UmbElementMixin with HTMLElement
88+
// This gives us all the helpers we need to get or consume contexts
89+
export default class ExampleElement extends UmbElementMixin(HTMLElement) {
90+
constructor() {
91+
super();
92+
this.attachShadow({ mode: 'open' });
93+
this.#render();
94+
}
95+
96+
#render() {
97+
if (!this.shadowRoot)
98+
return;
99+
100+
this.shadowRoot.innerHTML = `
101+
<uui-button look="primary" color="default" id="notificationButton">
102+
Click me for a notification!
103+
</uui-button>
104+
`;
105+
106+
const button = this.shadowRoot.querySelector('#notificationButton');
107+
button?.addEventListener('click', this.#notificationButtonClick.bind(this));
108+
}
109+
110+
async #notificationButtonClick(event: Event) {
111+
const notificationContext = await this.getContext(UMB_NOTIFICATION_CONTEXT);
112+
if (!notificationContext) {
113+
throw new Error('Notification context not found!');
114+
}
115+
116+
notificationContext?.peek("positive", {
117+
data: {
118+
headline: "Success",
119+
message: "The notification button was clicked successfully!"
120+
}
121+
});
122+
}
123+
}
124+
125+
// Register the custom element
126+
customElements.define('example-element', ExampleElement);
127+
```
128+
{% endtab %}
129+
{% endtabs %}
25130

26131
### Get context as a subscription
27132
If you intend to get a context and hold on to it during the lifetime if your component, you want to consume it. This means that you get an active subscription to the context with the supplied token. When the context changes or is disconnected, you get notified of it.

0 commit comments

Comments
 (0)