ソースを参照

Document destroy method in Alpine.data (#3716)

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.
Maritaria 1 年間 前
コミット
cb580d7c97
1 ファイル変更37 行追加0 行削除
  1. 37 0
      packages/docs/src/en/globals/alpine-data.md

+ 37 - 0
packages/docs/src/en/globals/alpine-data.md

@@ -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