SSE Events
Responses to backend actions with a content type of text/event-stream can contain zero or more Datastar SSE events.
The backend SDKs can handle the formatting of SSE events for you, or you can format them yourself.
Event Types #
datastar-patch-elements #
Patches one or more elements in the DOM. By default, Datastar morphs elements by matching top-level elements based on their ID.
In the example above, the element <div id="foo">Hello world!</div> will be morphed into the target element with ID foo.
Be sure to place IDs on top-level elements to be morphed, as well as on elements within them that you’d like to preserve state on (event listeners, CSS transitions, etc.).
Morphing elements within SVG elements requires special handling due to XML namespaces. See the SVG morphing example.
Additional data lines can be added to the response to override the default behavior.
| Key | Description |
|---|---|
data: selector #foo | Selects the target element of the patch using a CSS selector. Not required when using the outer or replace modes. |
data: mode outer | Morphs the outer HTML of the elements. This is the default (and recommended) mode. |
data: mode inner | Morphs the inner HTML of the elements. |
data: mode replace | Replaces the outer HTML of the elements. |
data: mode prepend | Prepends the elements to the target’s children. |
data: mode append | Appends the elements to the target’s children. |
data: mode before | Inserts the elements before the target as siblings. |
data: mode after | Inserts the elements after the target as siblings. |
data: mode remove | Removes the target elements from DOM. |
data: namespace svg | Patch elements into the DOM using an svg namespace. |
data: namespace mathml | Patch elements into the DOM using a mathml namespace. |
data: useViewTransition true | Whether to use view transitions when patching elements. Defaults to false. |
data: elements | The HTML elements to patch. |
Elements can be removed using the remove mode and providing a selector.
Elements can span multiple lines. Sample output showing non-default options:
Elements can be patched using svg and mathml namespaces by specifying the namespace data line.
datastar-patch-signals #
Patches signals into the existing signals on the page. The onlyIfMissing line determines whether to update each signal with the new value only if a signal with that name does not yet exist. The signals line should be a valid data-signals attribute.
Signals can be removed by setting their values to null.
Sample output showing non-default options: