Consume a Context
Learn how to consume contexts in Umbraco elements using one-time references or subscriptions to access data and functionality through the Context API.
Consuming contexts in an element
Get as one-time reference
import { UMB_NOTIFICATION_CONTEXT } from '@umbraco-cms/backoffice/notification';
import { html } from '@umbraco-cms/backoffice/external/lit';
import { UmbLitElement } from '@umbraco-cms/backoffice/lit-element';
//The example element extends the UmbLitElement (which is the same as UmbElementMixin(LitElement))
//This gives us all the helpers we need to get or consume contexts
export default class ExampleElement extends UmbLitElement {
/** Notification handler for the notification button */
async #notificationButtonClick() {
//We try to get an instance of the context
const notificationContext = await this.getContext(UMB_NOTIFICATION_CONTEXT);
if (!notificationContext) {
throw new Error('Notification context not found!');
}
notificationContext?.peek("positive", {
data: {
headline: "Success",
message: "The notification button was clicked successfully!"
}
});
//The notification is sent, now forget the context
}
/**
* Renders the lit component
* @see https://lit.dev/docs/components/rendering/
*/
render() {
return html`
<uui-button look="primary" color="default" @click="${this.#notificationButtonClick}">
Click me for a notification!
</uui-button>
`;
}
}
// Register the custom element
customElements.define('example-element', ExampleElement);Get as a subscription
Consuming contexts in non-UI elements
Get as one-time reference
Get as a subscription
Manual context control
Get as one-time reference
Get as a subscription
Last updated
Was this helpful?