> For the complete documentation index, see [llms.txt](https://docs.decentraland.org/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.decentraland.org/creator/content-creator-pt/scenes-sdk7/arquitetura/subscribe-to-changes.md).

# Inscrever-se nas Alterações

Detecte alterações em um component e execute funções a cada alteração

Uma forma elegante de escrever o seu código é subscrever-se a eventos e executar uma função sempre que esse evento ocorrer.

Uma série de [Listeners de eventos](https://docs.decentraland.org/creator/content-creator-pt/scenes-sdk7/interatividade/event-listeners.md) já vêm predefinidos como parte do SDK, mas também pode usar o `onChange()` método em qualquer componente para obter o mesmo resultado. Isto também funciona com qualquer [Componente personalizado](https://docs.decentraland.org/creator/content-creator-pt/scenes-sdk7/arquitetura/custom-components.md) que tenha definido, sem precisar de fazer mais nada.

Por exemplo, a função seguinte verifica o componente `AvatarEquippedData` na entidade do jogador e executa uma função se o jogador alterar algum dos Wearables ou Emotes que tem equipados. Os novos valores do componente são passados como argumentos da função.

```ts
import { AvatarEquippedData } from '@dcl/sdk/ecs'

export function main() {
	AvatarEquippedData.onChange(engine.PlayerEntity, (equipped) => {
		if (!equipped) return
		console.log('New wearables list: ', equipped.wearableUrns)
		console.log('New emotes list : ', equipped.emoteUrns)
	})
}
```

Graças ao `onChange()` método, não é necessário criar um sistema e verificar iterativamente os novos valores em cada frame, o que simplifica bastante este caso de uso muito comum.

{% hint style="warning" %}
**📔 Nota**: Não use `onChange()` dentro de um System, pois isso subscreveria uma nova cópia da função em cada frame do ciclo do jogo e poderia causar falhas.
{% endhint %}

O mesmo método funciona imediatamente com [Componentes personalizados](https://docs.decentraland.org/creator/content-creator-pt/scenes-sdk7/arquitetura/custom-components.md). Por exemplo:

```ts
// define component
export const MyComponent = engine.defineComponent('myComponent', {
	value1: Schemas.Boolean,
	value2: Schemas.Float,
})

// Uso
export function main() {
	// Criar Entities
	const myEntity = engine.addEntity()

	// Create instances of the component
	MyComponent.create(myEntity, {
		value1: true,
		value2: 10,
	})

	// Subscrever-se a alterações
	MyComponent.onChange(myEntity, (componentData) => {
		if (!componentData) return
		console.log(componentData.value1)
		console.log(componentData.value2)
	})
}
```

Também pode combinar esta abordagem com [consultas de componentes](https://docs.decentraland.org/creator/content-creator-pt/scenes-sdk7/arquitetura/querying-components.md), para subscrever em massa uma função própria para cada entidade da cena que tenha um determinado componente.

```ts
export function main() {
	for (const [entity] of engine.getEntitiesWith(MyComponent)) {
		MyComponent.onChange(entity, (componentData) => {
			if (!componentData) return
			console.log(componentData.value1)
			console.log(componentData.value2)
		})
	}
}
```

Tenha em atenção que esta abordagem só subscreve `onChange()` para entidades que existam no início da cena, como, por exemplo, entidades criadas através da interface do [Creator Hub](https://docs.decentraland.org/creator/content-creator-pt/scene-editor/primeiros-passos/about-editor.md).

{% hint style="info" %}
**💡 Sugestão**: Se preferir tratar eventos que não estejam necessariamente relacionados com a alteração de um componente, recomendamos importar a biblioteca TypeScript [Mitt](https://www.npmjs.com/package/mitt) para a sua cena. Esta biblioteca oferece funções simples para emitir e escutar eventos.
{% endhint %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.decentraland.org/creator/content-creator-pt/scenes-sdk7/arquitetura/subscribe-to-changes.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
