Skip to main content

d-unmount

The d-unmount directive allows the execution of JavaScript logic when an element is unmounted. This is useful for cleanup tasks such as removing event listeners, canceling network requests, or executing specific functions when an element is removed from the DOM.

Syntax

<div d-if="isVisible" d-unmount="handleCleanup">
This element will trigger cleanup when unmounted
</div>

Behavior

  • The directive evaluates the provided expression when the element is removed from the DOM.
  • If the expression is a function, it is executed.
  • Works well for managing resources that should be cleaned up when an element unmounts.

Use Case

d-unmount is ideal for scenarios where cleanup tasks are required, such as:

  • Removing event listeners
  • Cleaning up animations or subscriptions
  • Cancelling ongoing API requests

Example

<div d-scope="{cleanup: () => alert('Cleanup executed'), isVisible: true}">
<button @click="isVisible = !isVisible">Toggle</button>
<p d-if="isVisible" d-unmount="cleanup()">This element triggers cleanup on unmount</p>
</div>