Skip to content

Regaez/data-on-remove

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

8 Commits
 
 
 
 
 
 
 
 

Repository files navigation

data-on-remove

A custom Datastar attribute plugin that runs an expression when the element is removed from the DOM.

Live demo

<button
  data-on:click="el.remove()"
  data-on-remove="console.log('I removed myself', el)"
>
  Click to remove
</button>

Getting started

The plugin expects you to provide an import map that specifies the location of the datastar module. For example:

<script type="importmap">
  {
    "imports": {
      "datastar": "https://cdn.jsdelivr.net/gh/starfederation/[email protected]/bundles/datastar.js"
    }
  }
</script>
<script type="module" src="https://cdn.jsdelivr.net/gh/regaez/[email protected]/data-on-remove.min.js"></script>

Why use this plugin?

There are various reasons, some better than others, why you might want to be able to run an expression when an element is removed from the DOM. For example:

  1. Performance telemetry; measure client-side performance, e.g. the time between when a user interaction starts and when the server responds with a PatchElements event that removes some HTML.
  2. Security/monitoring; perhaps you are displaying some sensitive information, such as access tokens, payment information, etc., and want the client to confirm with the server that the content is no longer shown, instead of blindly trusting that a PatchElements event was successful.
  3. Signal cleanup; you may need the client to delete signals when the only component they are associated with no longer exists on the page (Disclaimer: if you care about following an idiomatic Datastar approach, this is likely not necessary, or may be better accomplished by your server via a PatchSignals event).

Documentation

The data-on-remove attribute runs Datastar expressions when the element it is attached to is removed from the DOM. Within these expressions, you have access to the following special variables:

  • el; the element that the data-on-remove attribute was attached to.
  • parent; the element that was the parent of the removed node

If the data-on-remove attribute is removed from the element prior to the element itself being removed, then the expression will not run.

Example

<section>
  <button
    data-on:click="el.remove()"
    data-on-remove="console.log({ el, parent })"
  >
    Click to remove
  </button>
<section>

When the button is clicked, this will log { el: button, parent: section } to the console.

Since the expression is executed after the element has already been removed from the DOM, you cannot access the parent via el.parentElement, so it is provided for you by the plugin.

View live demo examples here

License

MIT

About

A custom Datastar attribute plugin that runs an expression when the element is removed from the DOM.

Topics

Resources

License

Stars

Watchers

Forks