From 53f0e32b1133e6e5e2bc2a2e241bc466ad98f616 Mon Sep 17 00:00:00 2001 From: Maritaria Date: Mon, 21 Aug 2023 11:18:03 +0200 Subject: [PATCH] Document destroy method in Alpine.data Document the `destroy()` method of components on the docs page for `Alpine.data`. Includes an example allowing the reader to easily play and experiment with the behavior. --- packages/docs/src/en/globals/alpine-data.md | 37 +++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/packages/docs/src/en/globals/alpine-data.md b/packages/docs/src/en/globals/alpine-data.md index 51e40a6d9..d2b84dc35 100644 --- a/packages/docs/src/en/globals/alpine-data.md +++ b/packages/docs/src/en/globals/alpine-data.md @@ -87,6 +87,43 @@ Alpine.data('dropdown', () => ({ })) ``` + +## 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 + + + + + +``` + ## Using magic properties