Skip to content

useMutation

ts
useMutation(target: Node, init?: MutationObserverInit): Service<MutationProps>

A general MutationObserver as a service, for "tell me when anything under this node changes".

Props

ts
interface MutationProps {
  readonly records: readonly MutationRecord[];
}

The default observation is { childList: true, subtree: true }.

Usage

js
import { 
Base
,
useMutation
} from '@studiometa/js-toolkit';
class
Counter
extends
Base
{
static
config
= {
name
: 'Counter',
refs
: ['list'] };
mounted
() {
return
useMutation
(this.
$el
, {
childList
: true }).
subscribe
(({
records
}) => {
this.
$el
.
dataset
.
count
=
String
(this.
$el
.
children
.
length
);
}); } }

Reach for something narrower first

WantUse
one attribute of one elementwatchAttributes()
a whole namespace of attributeswatchAttributeNamespace()
what the framework already reconcilesthe registry — it is already watching
a subtree, character data, or a foreign nodethis

It keeps nothing after the delivery

props() is empty between deliveries, so { immediate: true } waits for a real batch rather than inventing one. That is the honest answer for a service whose value is a batch.

Platform timing, not framework order

This service delivers on the platform's timing. A subscriber that needs the framework's order awaits whenDOMSettled() in its callback:

js
useMutation(el).subscribe(async () => {
  await whenDOMSettled();
  // the new components have mounted
});

Keying

Its key is a canonical init, through resolveInit(), which keeps the DOM contract rather than sorting the object blindly. See perTarget().

Mixin

js
class Counter extends withMutation(Base, { childList: true }) {
  mutated({ records }) {}
}

MIT Licensed