Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions packages/docs/src/en/globals/alpine-data.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,43 @@ Alpine.data('dropdown', () => ({
}))
```

<a name="destroy-functions"></a>
## Destroy functions

If your component contains a `destroy()` method, Alpine will automatically execute it before cleaning up the component.

A primary example for this is when registering an event handler with another library or a browser API that isn't available through Alpine.
See the following example code on how to use the `destroy()` method to clean up such a handler.

```js
Alpine.data('timer', () => ({
timer: null,
counter: 0,
init() {
// Register an event handler that references the component instance
this.timer = setInterval(() => {
console.log('Increased counter to', ++this.counter);
}, 1000);
},
destroy() {
// Detach the handler, avoiding memory and side-effect leakage
clearInterval(this.timer);
},
}))
```

An example where a component is destroyed is when using one inside an `x-if`:

```html
<span x-data="{ enabled: false }">
<button @click.prevent="enabled = !enabled">Toggle</button>

<template x-if="enabled">
<span x-data="timer" x-text="counter"></span>
</template>
</span>
```

<a name="using-magic-properties"></a>
## Using magic properties

Expand Down