К основному содержанию
правило официальный · GitHub

pcf-events — правило для GitHub Copilot: события в PCF-компонентах

Правило подсказывает Copilot, как объявлять и обрабатывать кастомные события в компонентах Power Apps Component Framework.

Установить в GitHub Copilot · Вручную: положить файлы Все способы и платформы ↓
.github/instructions/pcf-events.instructions.md
Открыть на GitHub

Что делает pcf-events

Правило описывает механизм событий в PCF: компонент объявляет события в манифесте через элемент event, поднимает их в коде, а хост-приложение на них реагирует. В Canvas Apps подписка настраивается выражениями Power Fx в панели свойств контрола. В Model-Driven Apps обработчики вешаются методом addEventHandler через formContext.getControl(...).

Для Model-Driven Apps событие может нести payload — например, callback-функцию, чтобы скрипт-обработчик мог вернуться в компонент. События срабатывают отдельно для каждого экземпляра компонента на форме, это повод проверить логику, если контролов несколько.

Правило применяется к файлам **/*.{ts,tsx,js,json,xml,pcfproj,csproj}. Тема помечена как pre-release: документация может меняться, так что поведение стоит сверять с актуальной версией.

Какие задачи решает

  • объявить кастомное событие в манифесте PCF-компонента
  • подписаться на событие контрола в Model-Driven Apps через addEventHandler
  • настроить реакцию на событие в Canvas Apps через Power Fx
  • передать payload и callback из компонента в скрипт-обработчик
  • развести обработчики, когда на форме несколько экземпляров контрола

Примеры запросов агенту

  • добавь в манифест компонента событие customEvent1 и подними его в коде
  • покажи, как подписаться на customEvent1 через addEventHandler в Model-Driven Apps
  • как передать callback-функцию в payload события PCF-компонента

Как установить pcf-events

Вручную: положить файлы

.github/instructions/pcf-events.instructions.md

Поле applyTo задаёт, к каким файлам применять

По шагам, с командами для каждой платформы: AGENTS.md и CLAUDE.md: что это, кто читает и какой выбрать

Из того же набора732

Весь набор →
playwright-typescript Правило задаёт Copilot стиль написания тестов Playwright: ролевые локаторы, автоожидание, единая структура файлов. Пригодится, если тесты пишет агент, а не человек. ★ 40 418звёзд репо php-symfony Правило задаёт Copilot стиль разработки на Symfony: структура проекта, DI, Doctrine, Twig и тесты. Пригодится, если не хочется объяснять агенту конвенции в каждом чате. ★ 40 418звёзд репо pcf-tooling Правило подсказывает Copilot, что для сборки, отладки и деплоя код-компонентов нужен Microsoft Power Platform CLI. ★ 40 418звёзд репо pcf-manifest-schema Правило подсказывает Copilot структуру ControlManifest.Input.xml: какие элементы и атрибуты бывают и что они делают. Пригодится, когда правишь манифест PCF-компонента. ★ 40 418звёзд репо pcf-code-components Правило объясняет Copilot, как устроены code components в Power Apps component framework: манифест, реализация, ресурсы. Пригодится, когда правите ControlManifest.Input.xml или index.ts. ★ 40 418звёзд репо oop-design-patterns Правило для GitHub Copilot, которое подталкивает его к паттернам GoF и принципам SOLID при генерации и рефакторинге ООП-кода. ★ 40 418звёзд репо no-heredoc Правило запрещает агенту писать файлы через heredoc и перенаправления в терминале, потому что в VS Code такие команды портят содержимое. ★ 40 418звёзд репо nestjs Правило подключает к GitHub Copilot набор стандартов NestJS: модули, DI, DTO и валидация. Пригодится, когда агент пишет серверный код на TypeScript. ★ 40 418звёзд репо

Похожие

inngest-events inngest Помогает проектировать событийные воркфлоу Inngest: имена событий, идемпотентность по id, fan-out и системные события. CX Codex +1 3 800установок pixijs-events pixijs Скилл для работы с указателем, мышью, тачем и колесом в PixiJS v8: режимы eventMode, типы FederatedEvent, всплытие и перехват, hitArea, курсоры, drag через globalpointermove. CX Codex +1 5 900установок gws-events официальный googleworkspace Скилл подключает Google Workspace Events к агенту: подписки, операции и потоковые обновления задач. Нужен для работы с событиями через gws. CX Codex +1 31 500установок gws-events-subscribe официальный googleworkspace Скилл запускает подписку на события Google Workspace и отдаёт их потоком NDJSON. Пригодится, когда агенту нужно следить за чатами и другими ресурсами. CX Codex +1 30 800установок events-system phaserjs Помогает работать с системой событий Phaser 4: подписками, пользовательскими сигналами и обменом между сценами. Нужен при работе с on, emit и EventEmitter. CX Codex +1 783установок llmquant-events LLMQuant Скилл-маршрутизатор для событийных сценариев: подскажет, какой рабочий процесс открыть под отчётность, M&A или регуляторный риск. CX Codex +1 488установок

Рядом в теме «Фронтенд и UI»

Все правила IDE по теме «Фронтенд и UI» →

Вопросы о pcf-events

Как установить pcf-events в GitHub Copilot?

Положите файл по пути .github/instructions/pcf-events.instructions.md в репозитории — Copilot подхватит правило для файлов, подходящих под applyTo.

Что делает pcf-events?

Описывает объявление и обработку кастомных событий в PCF-компонентах: элемент event в манифесте, подписку в Canvas Apps и Model-Driven Apps, передачу payload.

Для каких файлов работает правило?

Для **/*.{ts,tsx,js,json,xml,pcfproj,csproj} — так задан applyTo в его frontmatter.

Исходный текст

pcf-events.instructions.md · MIT
---
description: 'Define and handle custom events in PCF components'
applyTo: '**/*.{ts,tsx,js,json,xml,pcfproj,csproj}'
---

# Define Events (Preview)

[This topic is pre-release documentation and is subject to change.]

A common requirement when building custom components with the Power Apps Component Framework is the ability to react to events generated within the control. These events can be invoked either due to user interaction or programmatically via code. For example, an application can have a code component that lets a user build a product bundle. This component can also raise an event which could show product information in another area of the application.

## Component Data Flow

The common data flow for a code component is data flowing from the hosting application into the control as inputs and updated data flowing out of the control to the hosting form or page. This diagram shows the standard pattern of data flow for a typical PCF component:

![Shows that data update from the code component to the binding field triggers the OnChange event](https://learn.microsoft.com/en-us/power-apps/developer/component-framework/media/component-events-onchange-example.png)

The data update from the code component to the bound field triggers the `OnChange` event. For most component scenarios, this is enough and makers just add a handler to trigger subsequent actions. However, a more complicated control might require events to be raised that aren't field updates. The event mechanism allows code components to define events that have separate event handlers.

## Using Events

The event mechanism in PCF is based on the standard event model in JavaScript. The component can define events in the manifest file and raise these events in the code. The hosting application can listen to these events and react to them.

### Define Events in Manifest

The component defines events using the [event element](https://learn.microsoft.com/en-us/power-apps/developer/component-framework/manifest-schema-reference/event) in the manifest file. This data allows the respective hosting application to react to events in different ways.

```xml
<property
  name="sampleProperty"
  display-name-key="Property_Display_Key"
  description-key="Property_Desc_Key"
  of-type="SingleLine.Text"
  usage="bound"
  required="true"
/>
<event
  name="customEvent1"
  display-name-key="customEvent1"
  description-key="customEvent1"
/>
<event
  name="customEvent2"
  display-name-key="customEvent2"
  description-key="customEvent2"
/>
```

### Canvas Apps Event Handling

Canvas apps react to the event using Power Fx expressions:

![Shows the custom events in the canvas apps designer](https://learn.microsoft.com/en-us/power-apps/developer/component-framework/media/custom-events-in-canvas-designer.png)

### Model-Driven Apps Event Handling

Model Driven Apps use the [addEventHandler method](https://learn.microsoft.com/en-us/power-apps/developer/model-driven-apps/clientapi/reference/controls/addeventhandler) to associate event handlers to custom events for a component.

```javascript
const controlName1 = "cr116_personid";

this.onLoad = function (executionContext) {
  const formContext = executionContext.getFormContext();

  const sampleControl1 = formContext.getControl(controlName1);
  sampleControl1.addEventHandler("customEvent1", this.onSampleControl1CustomEvent1);
  sampleControl1.addEventHandler("customEvent2", this.onSampleControl1CustomEvent2);
}
```

> **Note**: These events occur separately for each instance of the code component in the app.

## Defining an Event for Model-Driven Apps

For model-driven apps you can pass a payload with the event allowing for more complex scenarios. For example in the diagram below the component passes a callback function in the event allowing the script handling to call back to the component.

![In this example, the component passes a callback function in the event allowing the script handling to call back to the component](https://learn.microsoft.com/en-us/power-apps/developer/component-framework/media/passing-payload-in-events.png)

```javascript
this.onSampleControl1CustomEvent1 = function (params) {
   //alert(`SampleControl1 Custom Event 1: ${params}`);
   alert(`SampleControl1 Custom Event 1`);
}.bind(this);

this.onSampleControl2CustomEvent2 = function (params) {
  alert(`SampleControl2 Custom Event 2: ${params.message}`);
  // prevent the default action for the event
  params.callBackFunction();
}
```

## Defining an Event for Canvas Apps

Makers configure an event using Power Fx on the PCF control in the properties pane.

## Calling an Event

See how to call an event in [Events](https://learn.microsoft.com/en-us/power-apps/developer/component-framework/reference/events).

## Next Steps

[Tutorial: Define a custom event in a component](https://learn.microsoft.com/en-us/power-apps/developer/component-framework/tutorial-define-event)

© github · MIT · github/awesome-copilot

Смотрите также

Спонсоры проекта

Компании, которые помогают держать аналитику открытой