deepchange event

The deepchange event fires on live variables when a variable itself or one of its nested properties has changed.

This is a relatively low-level way of interacting with live variables; often, using an effect() is more appropriate.

Syntax

when($live).deepchanges().then(event => { // … }); $live.addEventListener('deepchange', event => { // … });

Event details

This event exposes no additional details; it dispatches a generic native CustomEvent instance.

Examples

A live object in localStorage

Let's say we have a live object (with nested properties) and we'd like to remember this object across page visits. To do this, we'll place it in localStorage and update the respective localStorage key every time the object changes.

const initial = { foo: { bar: 23 }}; const stored = JSON.parse(localStorage.getItem('object')); const $object = live(stored ?? fallback); when($object).deepchanges().then(() => { const stringified = JSON.stringify(live.get($object)); localStorage.setItem('object', stringified); });

Now, when changing a nested property on our object (like $object.$foo.bar = 44), then the listener triggers and saves the object in localStorage. Had we used the change event instead, then the listener would have fired only when the value for the object itself changes (e.g. through live.set($object, {})), rather than for all nested properties in the object.

Usage notes

The deepchange event fires once for every synchronous change. In other words, if there are multiple nested changes (e.g. through assigning an object that changes multiple properties) the deepchange event will still only fire once. If a live variable dispatches either the keychange or the change event, then the deepchange event is guaranteed to fire as well, and will do so after any keychange and change events. Specifically, if all three fire on a single live variable, then the keychange event is first, followed by the change event, and lastly the deepchange event.

While the deepchange event seems to bubble (similarly to how events bubble on DOM elements), it is not "real" event bubbling; the dispatched events are different CustomEvent instances. As such, you cannot stop the propagation (calling .stopPropagation() on a deepchange event does nothing).

See also