umbraco-context-api

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Umbraco Context API

Umbraco Context API

What is it?

什么是Context API?

The Context API is Umbraco's communication system that enables extensions to share data and functionality through the component hierarchy without tight coupling. It uses a provider-consumer pattern where parent elements provide contexts that descendant components can access. Contexts cascade down through the DOM tree and use tokens for type-safe access to services like notifications, workspaces, and user information.
Context API是Umbraco的通信系统,它允许扩展程序通过组件层级结构共享数据和功能,无需紧密耦合。它采用提供者-消费者模式,父元素提供上下文,子组件可以访问这些上下文。上下文会沿着DOM树向下传递,并使用令牌(token)实现对通知、工作区和用户信息等服务的类型安全访问。

Documentation

文档

Workflow

工作流程

  1. Fetch docs - Use WebFetch on the URLs above
  2. Ask questions - Need to consume or provide? Which context? One-time or subscription?
  3. Generate code - Implement context consumption or provision based on latest docs
  4. Explain - Show what was created and how contexts flow
  1. 获取文档 - 使用WebFetch访问上述URL
  2. 提出问题 - 需要消费还是提供上下文?要使用哪个上下文?一次性获取还是订阅?
  3. 生成代码 - 根据最新文档实现上下文的消费或提供
  4. 解释说明 - 展示创建的内容以及上下文的流转方式

Minimal Examples

最小示例

Consuming Context (Subscription Pattern)

消费上下文(订阅模式)

typescript
import { UmbLitElement } from '@umbraco-cms/backoffice/lit-element';
import { UMB_NOTIFICATION_CONTEXT } from '@umbraco-cms/backoffice/notification';

export class MyElement extends UmbLitElement {
  #notificationContext?: typeof UMB_NOTIFICATION_CONTEXT.TYPE;

  constructor() {
    super();

    // Subscribe to context - callback runs when context is available
    this.consumeContext(UMB_NOTIFICATION_CONTEXT, (context) => {
      this.#notificationContext = context;
    });
  }

  showMessage() {
    this.#notificationContext?.peek('positive', {
      data: { message: 'Hello from Context API!' }
    });
  }
}
typescript
import { UmbLitElement } from '@umbraco-cms/backoffice/lit-element';
import { UMB_NOTIFICATION_CONTEXT } from '@umbraco-cms/backoffice/notification';

export class MyElement extends UmbLitElement {
  #notificationContext?: typeof UMB_NOTIFICATION_CONTEXT.TYPE;

  constructor() {
    super();

    // Subscribe to context - callback runs when context is available
    this.consumeContext(UMB_NOTIFICATION_CONTEXT, (context) => {
      this.#notificationContext = context;
    });
  }

  showMessage() {
    this.#notificationContext?.peek('positive', {
      data: { message: 'Hello from Context API!' }
    });
  }
}

Consuming Context (One-time Pattern)

消费上下文(一次性模式)

typescript
import { UmbControllerBase } from '@umbraco-cms/backoffice/class-api';
import { UMB_NOTIFICATION_CONTEXT } from '@umbraco-cms/backoffice/notification';

export class MyService extends UmbControllerBase {
  async showNotification(text: string) {
    // Get context once, use it, then release
    const context = await this.getContext(UMB_NOTIFICATION_CONTEXT);
    context?.peek('positive', { data: { message: text } });
  }
}
typescript
import { UmbControllerBase } from '@umbraco-cms/backoffice/class-api';
import { UMB_NOTIFICATION_CONTEXT } from '@umbraco-cms/backoffice/notification';

export class MyService extends UmbControllerBase {
  async showNotification(text: string) {
    // Get context once, use it, then release
    const context = await this.getContext(UMB_NOTIFICATION_CONTEXT);
    context?.peek('positive', { data: { message: text } });
  }
}

Providing Context

提供上下文

typescript
import { UmbLitElement } from '@umbraco-cms/backoffice/lit-element';
import { UmbContextToken } from '@umbraco-cms/backoffice/context-api';

// Define a context token
export const MY_CUSTOM_CONTEXT = new UmbContextToken<MyCustomContext>(
  'MyCustomContext'
);

export class MyCustomContext {
  getData() {
    return { message: 'Hello from custom context!' };
  }
}

export class MyProviderElement extends UmbLitElement {
  constructor() {
    super();

    // Provide context to all descendants
    this.provideContext(MY_CUSTOM_CONTEXT, new MyCustomContext());
  }
}
typescript
import { UmbLitElement } from '@umbraco-cms/backoffice/lit-element';
import { UmbContextToken } from '@umbraco-cms/backoffice/context-api';

// Define a context token
export const MY_CUSTOM_CONTEXT = new UmbContextToken<MyCustomContext>(
  'MyCustomContext'
);

export class MyCustomContext {
  getData() {
    return { message: 'Hello from custom context!' };
  }
}

export class MyProviderElement extends UmbLitElement {
  constructor() {
    super();

    // Provide context to all descendants
    this.provideContext(MY_CUSTOM_CONTEXT, new MyCustomContext());
  }
}

Common Built-in Contexts

常见内置上下文

typescript
// Notifications
import { UMB_NOTIFICATION_CONTEXT } from '@umbraco-cms/backoffice/notification';

// Current User
import { UMB_CURRENT_USER_CONTEXT } from '@umbraco-cms/backoffice/current-user';

// Modal Manager
import { UMB_MODAL_MANAGER_CONTEXT } from '@umbraco-cms/backoffice/modal';

// Workspace (varies by type)
import { UMB_DOCUMENT_WORKSPACE_CONTEXT } from '@umbraco-cms/backoffice/document';

// Block Entry (for block editors)
import { UMB_BLOCK_ENTRY_CONTEXT } from '@umbraco-cms/backoffice/block';

// Property Dataset (for property editors)
import { UMB_PROPERTY_DATASET_CONTEXT } from '@umbraco-cms/backoffice/property';
typescript
// Notifications
import { UMB_NOTIFICATION_CONTEXT } from '@umbraco-cms/backoffice/notification';

// Current User
import { UMB_CURRENT_USER_CONTEXT } from '@umbraco-cms/backoffice/current-user';

// Modal Manager
import { UMB_MODAL_MANAGER_CONTEXT } from '@umbraco-cms/backoffice/modal';

// Workspace (varies by type)
import { UMB_DOCUMENT_WORKSPACE_CONTEXT } from '@umbraco-cms/backoffice/document';

// Block Entry (for block editors)
import { UMB_BLOCK_ENTRY_CONTEXT } from '@umbraco-cms/backoffice/block';

// Property Dataset (for property editors)
import { UMB_PROPERTY_DATASET_CONTEXT } from '@umbraco-cms/backoffice/property';

Key Concepts

核心概念

Context Token: Type-safe identifier for a context
typescript
const MY_TOKEN = new UmbContextToken<MyType>('UniqueName');
Provider: Element that provides context to descendants via
provideContext()
Consumer: Element that accesses context via
consumeContext()
or
getContext()
Subscription vs One-time:
  • Use
    consumeContext()
    when you need the context during initialization
  • Use
    getContext()
    for actions triggered by user interaction
Hierarchy: Contexts flow DOWN the DOM tree from provider to consumers
That's it! Always fetch fresh docs, keep examples minimal, generate complete working code.
上下文令牌(Context Token):上下文的类型安全标识符
typescript
const MY_TOKEN = new UmbContextToken<MyType>('UniqueName');
提供者(Provider):通过
provideContext()
为子元素提供上下文的元素
消费者(Consumer):通过
consumeContext()
getContext()
访问上下文的元素
订阅 vs 一次性获取
  • 当初始化期间需要上下文时,使用
    consumeContext()
  • 对于用户交互触发的操作,使用
    getContext()
层级结构:上下文从提供者沿着DOM树向下流向消费者
就是这样!请务必获取最新文档,保持示例简洁,生成完整可运行的代码。