---
url: 'https://ambiki.github.io/impulse/introduction/what-is-impulse.md'
---
# What is Impulse?
Impulse is a lightweight JavaScript framework built on the [Web Components](https://developer.mozilla.org/en-US/docs/Web/API/Web_components)
API. Unlike traditional frameworks, it does not dictate how you render HTML. Instead, it augments your existing HTML
with just enough JavaScript to make it interactive and reactive.
Write your HTML however you like — server-rendered, static, or generated — and let Impulse handle the behavior.
## Mental model
Impulse leans on progressive enhancement. There is no virtual DOM and no JSX. You write a [custom element](/reference/registering-elements)
around your markup, then wire up behavior with a small set of building blocks:
* [**Actions**](/reference/actions) bind event listeners declaratively via `data-action` attributes.
* [**Targets**](/reference/targets) reference child elements by name via `data-target` attributes.
* [**Properties**](/reference/properties) read and write HTML attributes, with change callbacks.
* [**Lifecycle callbacks**](/reference/lifecycle-callbacks) run code when an element or target connects to or disconnects from the DOM.
## Example
This counter keeps the `count` attribute in sync with the component's property, calling `countChanged()` whenever it
updates:
```ts
import { ImpulseElement, property, registerElement, target } from '@ambiki/impulse';
@registerElement('counter-element')
export default class CounterElement extends ImpulseElement {
@property({ type: Number }) count = 0;
@target() output: HTMLElement;
countChanged(value: number) {
this.output.textContent = String(value);
}
decrement() {
this.count--;
}
increment() {
this.count++;
}
}
```
```html
Count: 0
```
No virtual DOM, no JSX — just progressive enhancement of your HTML.
## Coming from Stimulus?
If this looks like [Stimulus](https://stimulus.hotwired.dev/), that's no accident — Impulse borrows its best ideas, so
actions, targets, and attribute-backed properties will feel familiar. Stimulus is mature and battle-tested, and it
remains a great choice. Impulse makes a different set of trade-offs that grew out of building [Ambiki](https://www.ambiki.com):
* **Components are native custom elements.** A component *is* its element (``), so its methods live
on the DOM node — you can call them from anywhere, including existing jQuery code:
`document.querySelector('counter-element').increment()`. With Stimulus, the controller instance is not exposed on the
element, so reaching it from outside the framework is awkward.
* **First-class TypeScript.** Properties and targets are declared with typed decorators
(`@property({ type: Number }) count`, `@target() output: HTMLElement`) rather than stringly-typed statics.
* **A single shared DOM observer.** Impulse watches the document with one shared
[MutationObserver](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver), regardless of how many elements
are on the page. Stimulus instantiates several observers per controller instance, which added up on the dense,
long-lived pages we were building.
---
---
url: 'https://ambiki.github.io/impulse/introduction/getting-started.md'
---
# Getting started
## Installation
::: code-group
```sh [npm]
$ npm install @ambiki/impulse
```
```sh [pnpm]
$ pnpm add @ambiki/impulse
```
```sh [yarn]
$ yarn add @ambiki/impulse
```
```sh [bun]
$ bun add @ambiki/impulse
```
:::
Impulse's `@registerElement()`, `@property()`, `@target()`, and `@targets()` decorators work with either of
TypeScript's decorator conventions: the standard decorators TypeScript 5 and later compile by default, or the legacy
ones that `experimentalDecorators` turns on. With either, disable `strictPropertyInitialization`, so that declaring a
target or a property without an initializer is not an error.
::: code-group
```json [Standard decorators]
{
"compilerOptions": {
"strict": true,
"strictPropertyInitialization": false
}
}
```
```json [Legacy decorators]
{
"compilerOptions": {
"strict": true,
"experimentalDecorators": true,
"strictPropertyInitialization": false
}
}
```
:::
`useDefineForClassFields` can take either value. Impulse's types need TypeScript 5.0 or later, and standard decorators
need 5.2 or later, the first version to pass them decorator metadata. They keep what they declare on `Symbol.metadata`,
which Impulse defines when the browser doesn't.
Other compilers follow the same choice. esbuild, and Vite 7 and earlier with it, reads `experimentalDecorators` from
your `tsconfig.json`, and supports standard decorators from 0.21. Vite 8 compiles TypeScript with Oxc, which handles
legacy decorators but can't compile standard ones yet, so with Vite 8 use legacy decorators, or compile standard ones
with Babel as [Vite's migration guide](https://vite.dev/guide/migration) shows. With Babel, use
`@babel/plugin-proposal-decorators` with `version: '2023-11'` for standard decorators, or `version: 'legacy'` for legacy
ones, which also need `@babel/plugin-transform-class-properties` after it.
## Loading your elements
`@registerElement()` defines the element when its file runs, so import every element file from your application's entry
point (or load it with [`lazyImport`](/utilities/lazy-import)):
```ts
// application.ts
import './elements/clip_board_element';
import './elements/lazy_load_element';
```
## The descendant-wait warning
An element whose markup contains a custom element that is not defined yet logs a deprecation warning when it
initializes. See [`[target]Connected()`](/reference/lifecycle-callbacks#target-connected) for what to change and how to
silence it.
Upgrading from 1.x? See [Upgrading to 2.0](/introduction/upgrading-to-2).
---
---
url: 'https://ambiki.github.io/impulse/introduction/upgrading-to-2.md'
---
# Upgrading to 2.0
This page covers what you may need to change when moving from 1.x. See the
[changelog](https://github.com/Ambiki/impulse/blob/main/CHANGELOG.md) for the full list.
## Removed observer classes
`SelectorObserver`, `ElementObserver`, `AttributeObserver` and `TokenListObserver` are no longer exported. Use
[`connected`](/utilities/connected) and [`disconnected`](/utilities/disconnected) instead:
```ts
import { connected } from '@ambiki/impulse';
const stop = connected('[data-toggle="tooltip"]', (element) => {
$(element).tooltip();
return () => $(element).tooltip('dispose');
});
```
## `on` is delegated
[`on`](/utilities/on) now runs every handler from one listener on `document` instead of a listener on each matching
element.
* Events that do not bubble (`focus`, `blur`, `mouseenter`, `mouseleave`, `load`, `error`, `scroll`) need
`{ capture: true }`, or use `focusin` / `focusout` / `mouseover` / `mouseout`.
* `event.currentTarget` is the matched element, as before.
* Without `capture`, `event.stopPropagation()` in an `on` handler stops other `on` handlers, but not native listeners
on the elements between the target and `document`. A native listener that stops propagation keeps every bubbling
`on` handler from running.
## Nothing matches before the document is parsed
`connected`, `disconnected` and `lazyImport` match nothing while `document.readyState` is `loading`. Called from a
blocking `` script, their callbacks first run on `DOMContentLoaded`. On a long page, unenhanced content can show
briefly. See [before the document is parsed](/utilities/connected#before-the-document-is-parsed).
## Errors are reported, not thrown
A `connected`, `disconnected`, `lazyImport` or `[target]Connected()` / `[target]Disconnected()` callback that throws is
reported to `window.onerror` and no longer stops the other callbacks for the same DOM change. A duplicate `@target()` is
reported the same way instead of rejecting the element's initialization.
A selector the browser rejects throws a `DOMException` named `SyntaxError` at the call and registers nothing.
## The descendant wait is deprecated
Impulse still waits for undefined descendant custom elements before running `[target]Connected()` callbacks, but logs a
warning. If a callback reads a target's properties, await [`whenInitialized`](/utilities/when-initialized) instead, then
set `ImpulseElement.migratedToWhenInitialized = true`. See
[lifecycle callbacks](/reference/lifecycle-callbacks#target-connected).
---
---
url: 'https://ambiki.github.io/impulse/reference/registering-elements.md'
---
# Registering elements
Registering an element tells the browser to associate a tag name with your class. Use the `@registerElement()`
class decorator, passing the tag name you want to use in your HTML.
```ts{4}
// elements/clip_board_element.ts
import { ImpulseElement, registerElement } from '@ambiki/impulse';
@registerElement('clip-board')
export default class ClipBoardElement extends ImpulseElement {
// ...
}
```
```html
```
Under the hood, this calls [`customElements.define()`](https://developer.mozilla.org/en-US/docs/Web/API/CustomElementRegistry/define)
to register a [custom element](https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_custom_elements).
What it registers is a subclass of your class, which defines your [properties](/reference/properties) once the element
is constructed. With the decorator, the class name refers to that subclass, so `new ClipBoardElement()` and
`instanceof` work as usual. Called as a function, `registerElement('clip-board')(ClipBoardElement)`, it registers and
returns the subclass, so use what it returns. If the tag name is already defined, the call is ignored and the first
class stays registered.
## Tag names
The tag name must contain a hyphen — this is a requirement of the custom element spec, not Impulse. Names such as
`clipboard` or `popover` are invalid; use `clip-board` or `pop-over` instead.
The tag name is also the prefix you reference in [actions](/reference/actions) and [targets](/reference/targets):
```html
```
## Extending elements
An element class can extend another. It inherits every `@property()`, `@target()`, and `@targets()` of the classes it
extends, along with their methods, such as `[property]Changed()`:
```ts
class BaseInputElement extends ImpulseElement {
@property({ type: Boolean }) disabled = false;
@target() label: HTMLLabelElement | null;
disabledChanged(disabled: boolean) {
// ...
}
}
@registerElement('fancy-input')
export default class FancyInputElement extends BaseInputElement {
@property() placeholder = '';
}
```
`` observes both `disabled` and `placeholder`, and fills `label`. Only the classes used as elements need
`@registerElement()`.
Declaring an inherited field again replaces its declaration, even with another decorator: a subclass can give a
`@property()` another type, or make it a `@target()`. The superclass keeps its own. A class can declare a field only
once, so `@property() @target() label` throws when the class is defined.
::: warning Declaring a field again without an initializer
With `useDefineForClassFields`, which TypeScript turns on for ES2022 and later targets and Babel uses by default, a
field declared again without an initializer starts out `undefined`, replacing the value the superclass gave it. A
`@property()` then reads its empty value when its attribute is missing. Repeat the initializer:
```ts
class SearchInputElement extends BaseInputElement {
@property({ type: Boolean }) disabled = false;
}
```
To only narrow a field's type, without declaring it again, use `declare` instead (`declare label: HTMLLabelElement;`),
which compiles to nothing.
:::
---
---
url: 'https://ambiki.github.io/impulse/reference/lifecycle-callbacks.md'
---
# Lifecycle callbacks
Lifecycle callbacks let you respond whenever an element or target is connected to or disconnected from the DOM.
## Functions
When an element initializes, these functions are invoked in the order shown below, with actions bound after the
`[target]Connected()` callbacks and before `connected()`. Initialization waits until the document is parsed (see
[before the document is parsed](/utilities/connected#before-the-document-is-parsed)), so events fired on the element
before then are missed. A target added after the element has initialized gets its `[target]Connected()` call at that
point, after `connected()`.
### `constructor()`
This function is called when the element is created. Within this function, you can perform one-time initialization
tasks, such as declaring properties.
::: warning
You should not query the DOM within the `constructor` function and always call `super()` when using it.
:::
```ts
constructor() {
super();
this.interval = 500;
}
```
### `[target]Connected()`
This function is called when the declared `target` / `targets` is connected to the DOM. Within this function, you can
manipulate the target — most commonly setting HTML attributes and adding event listeners. Anything done here should be
undone when the target is disconnected from the DOM.
```ts
@target() panel: HTMLElement;
@targets() buttons: HTMLButtonElement[];
panelConnected(panel: HTMLElement) {
console.log('panel connected to the DOM: ', panel);
}
buttonsConnected(button: HTMLButtonElement) {
console.log('button connected to the DOM: ', button);
}
```
::: warning Deprecated behavior
When this callback fires, the target element is in the DOM, and its `@property` accessors exist if its class is defined.
It may not have finished initializing, though, and a target whose class is not defined yet (one loaded with
[`lazyImport`](/utilities/lazy-import), for example) has no accessors at all.
Today, each time an element initializes, Impulse waits for every undefined custom element inside it to be defined
before invoking these callbacks, binding actions and calling `connected()`. A descendant that is never defined, such as
a mistyped tag, keeps the element from initializing. Targets added later are not waited for. **This implicit wait is
deprecated and will be removed in the next major version.**
If a connected callback reads properties on a target element, await
[`whenInitialized`](/utilities/when-initialized) inside the callback instead:
```ts
async panelConnected(panel: PanelElement) {
await whenInitialized(panel);
console.log(panel.someProperty);
}
```
Once you have migrated, silence the deprecation warning by setting `ImpulseElement.migratedToWhenInitialized = true`,
or set `migratedToWhenInitialized` on a single element class. The flag only silences the warning; the wait still runs.
:::
### `connected()`
This function is called when the element itself is connected to the DOM. When this function is invoked, you can be sure
that all properties and targets have been resolved and added to the DOM, and
[`isInitialized(this)`](/utilities/is-initialized) is `true`. You can query the DOM within this function, set event
listeners, and do much more. Anything done within this function should be undone when the element is disconnected from
the DOM.
```ts
connected() {
this.addEventListener('click', this.handleClick);
}
```
::: warning Moving the element
Moving the element from inside `connected()`, such as a toast appending itself to a shared region, disconnects and
reconnects it. `disconnected()` runs, the element initializes again at its new position, and `connected()` is called a
second time. Guard the move: left unguarded, it loops without a pause and freezes the page.
```ts
connected() {
const region = document.getElementById('toasts')!;
if (this.parentElement !== region) region.append(this);
}
```
:::
### `disconnected()`
This function is called when the element itself is disconnected from the DOM. Within this function, you can clean up
any event listeners and tasks that were attached in the `connected()` function so that it is free to be garbage
collected.
```ts
disconnected() {
this.removeEventListener('click', this.handleClick);
}
```
By the time `disconnected()` runs, the element no longer counts as initialized: the `data-impulse-element` attribute is
gone, [`isInitialized(this)`](/utilities/is-initialized) is `false`, and `whenInitialized(this)` waits until the element
is connected and initialized again.
If `disconnected()` or a `[target]Disconnected()` callback throws, the element still finishes tearing down, so it can
initialize again when it reconnects. The first error is rethrown afterwards.
### `[target]Disconnected()`
This function is called when the declared `target` / `targets` is disconnected from the DOM. Within this function, you
can clean up any event listeners and tasks that were attached in the `[target]Connected()` function so that it is
free to be garbage collected.
```ts
@target() panel: HTMLElement;
@targets() buttons: HTMLButtonElement[];
panelDisconnected(panel: HTMLElement) {
console.log('panel disconnected from the DOM: ', panel);
}
buttonsDisconnected(button: HTMLButtonElement) {
console.log('button disconnected from the DOM: ', button);
}
```
---
---
url: 'https://ambiki.github.io/impulse/reference/actions.md'
---
# Actions
Actions let you bind event listeners to an element.
## Attributes and names
The `data-action` attribute is a space-separated list of action [descriptors](#descriptors) that defines how an element
should react when an event is fired on it.
```html{2}
```
```ts{6}
// elements/greet_user_element.ts
import { ImpulseElement, registerElement } from '@ambiki/impulse';
@registerElement('greet-user')
export default class GreetUserElement extends ImpulseElement {
greet(event: Event) {
//
}
}
```
## Descriptors
The `data-action` value `click->greet-user#greet` is called an action descriptor. In this descriptor:
* `click` is the name of the DOM event.
* `greet-user` is the name of the custom element.
* `greet` is the name of the function that should be invoked when the event is triggered.
The event name is required. There is no default event per element, so `greet-user#greet` is ignored.
An action is wired up by the closest ancestor (or the element itself) whose tag name matches the identifier in the
descriptor — `greet-user` above. A `data-action` that names an element it is not inside of is never bound to anything.
Actions are bound once that element has [initialized](/reference/lifecycle-callbacks#functions). An event fired before
then is missed.
An action on an element inserted later is bound when Impulse's `MutationObserver` delivers the insertion, not at the
moment of the `append()` call, so an event dispatched in the same synchronous run of script is missed too. Await a
microtask (`await Promise.resolve()`) between inserting the element and dispatching the event.
## Global events
You can add `@window` or `@document` to the descriptor to listen for events on the `window` or `document` respectively.
```html
```
## Event modifiers
You'll often call `event.preventDefault()` or `event.stopPropagation()` inside a handler. Declaring it in the action
descriptor is clearer, so Impulse provides these modifiers out of the box.
* `.stop`
* `.prevent`
* `.self`
* `.capture`
* `.once`
* `.passive`
```html
```
Modifiers run in the order written, and only when the method exists. `click.self.prevent` calls `preventDefault()` only
for clicks on the element itself, while `click.prevent.self` calls it for every click. Unknown modifiers are ignored.
The `.capture`, `.once`, and `.passive` modifiers mirror the [DOM event listener options](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#options).
```html
```
## Naming conventions
Always use camelCase to reference the action names.
```html
```
---
---
url: 'https://ambiki.github.io/impulse/reference/properties.md'
---
# Properties
Properties allow you to read and write HTML attributes. A `@property()` is defined on the element once it is
constructed. From then on, reading it reads the attribute and assigning it writes the attribute.
```html
```
```ts{6,9}
// elements/lazy_load_element.ts
import { ImpulseElement, registerElement, property } from '@ambiki/impulse';
@registerElement('lazy-load')
export default class LazyLoadElement extends ImpulseElement {
@property() src: string;
connected() {
console.log(this.src); // /users
}
}
```
## Change callbacks
When a property changes, its callback runs so you can react to the new value.
Define a `[property]Changed` function, where `[property]` is the property name. It receives `newValue` as the first
argument and `oldValue` as the second. It does not run for the value the element connects with, before it has
[initialized](/utilities/when-initialized), or once the element has been torn down after disconnecting. A change made
from `disconnected()` still runs it.
```ts{7}
import { ImpulseElement, registerElement, property } from '@ambiki/impulse';
@registerElement('lazy-load')
export default class LazyLoadElement extends ImpulseElement {
@property() src: string;
srcChanged(newValue: string, oldValue: string) {
// ...
}
}
```
The callback only runs when the converted value actually changes. An attribute write that reads back as the same
value is a no-op: `8_000` rewritten as `8000`, an `Array` or `Object` attribute reformatted (`{ "foo": "bar" }` to
`{"foo":"bar"}`, or its keys reordered), or an attribute removed when it already read as the default. `Array` and
`Object` values are compared structurally, so a server re-render that emits the same data in a different shape of JSON
does not re-trigger downstream effects.
## Types
A property can be one of `Array`, `Boolean`, `Number`, `Object`, or `String`, with `String` being the default.
```html
```
```ts{6-7,10-11}
// elements/pop_over_element.ts
import { ImpulseElement, registerElement, property } from '@ambiki/impulse';
@registerElement('pop-over')
export default class PopOverElement extends ImpulseElement {
@property({ type: Array }) placements: string[];
@property({ type: Boolean }) open: boolean = false;
connected() {
console.log(this.placements); // ['top', 'right']
console.log(this.open); // true
}
}
```
Attribute values are converted on read, so `this.property` and the value passed to the
[change callback](#change-callbacks) always agree. A missing attribute reads as the property's
[default](#default-property-values), and so does one that does not parse as its type: an empty or non-numeric
`Number`, or an `Array` or `Object` attribute that is not valid JSON of that kind. Any value is a valid `String`, the
empty one included. A `Boolean` attribute reads as `true` whenever it is present, unless its value is `"false"`.
## Default property values
Assign a value to the property to give it a default: what the property reads as while its attribute is missing.
```ts{5,8}
import { ImpulseElement, registerElement, property } from '@ambiki/impulse';
@registerElement('lazy-load')
export default class LazyLoadElement extends ImpulseElement {
@property() src = '/users';
connected() {
console.log(this.src); // /users
}
}
```
The default lives only in JavaScript. Connecting does not write it to the attribute, so `getAttribute('src')` returns
`null` and a selector such as `[src="/users"]` does not match. Render the attribute from the server when CSS or other
code needs to see it. Since the element holds no attribute the server's HTML lacks, a morph (a Turbo page refresh, for
example) that syncs the element to that HTML leaves its defaults alone.
If the attribute is present, it wins over the default. Once it is removed, by hand or by a morph, the property reads
the default again, and the change callback receives it.
A property without a default, or with `null` or `undefined` as its default, reads as its type's empty value: `''`,
`0`, `false`, `[]`, or `{}`. An `Array` or `Object` default is copied on every read, so mutating what the property
returns never changes the default.
A value assigned before the element connects, as in `element.open = true` on an element you just created, is not a
default: it is written to the attribute like any assignment. This takes `@registerElement`. A class registered with
`customElements.define` instead defines its properties when it first connects, so a value assigned before that
becomes the default.
## Assigning values
Assigning a property writes its attribute, even when the value equals the default:
```ts
element.src = '/posts'; // src="/posts"
element.src = '/users'; // src="/users"
element.src = null; // removes `src`, so `element.src` reads the default, '/users'
```
Assigning `null` or `undefined` removes the attribute, which resets the property to its default.
A `Boolean` set to `true` writes an empty attribute (`open=""`). Set to `false`, it removes the attribute, so `[open]`
selectors stop matching. A `Boolean` that defaults to `true` is the exception: a missing attribute would read as
`true`, so `false` is written as `flip="false"`.
## Naming conventions
Always use kebab-case in your HTML, and use camelCase in your `.ts` file.
```html
```
```ts{5}
import { ImpulseElement, registerElement, property } from '@ambiki/impulse';
@registerElement('lazy-load')
export default class LazyLoadElement extends ImpulseElement {
@property() contentType: string;
}
```
An acronym dasherizes as one word: `fooURL` reads the `foo-url` attribute, and its change callback is `fooURLChanged`.
Two properties that dasherize alike, such as `fooURL` and `fooUrl`, read the same attribute, and a change to it calls
both callbacks.
---
---
url: 'https://ambiki.github.io/impulse/reference/targets.md'
---
# Targets
Targets let you reference element(s) by name.
## Attributes and names
The `data-target` attribute is a space-separated list of target names that can be referenced in the element.
```html{2,3}
```
## Shared targets
An element can have multiple target references.
```html{3,4}
```
## Single target
A single target can be referenced via the `@target()` decorator. Once the element has
[initialized](/utilities/when-initialized), the property is the matching element, or `null` while none is present.
Before that, it is `undefined`.
```html{2}
```
```ts{6}
// elements/greet_user_element.ts
import { ImpulseElement, registerElement, target } from '@ambiki/impulse';
@registerElement('greet-user')
export default class GreetUserElement extends ImpulseElement {
@target() result: HTMLElement;
// ...
}
```
A `@target()` property points at one element. A second element carrying the same target name waits: it stays out of the
property until the target is removed or stops carrying the name, and is then adopted, getting its own
[connected callback](#connected-and-disconnected-callbacks). When several wait, the first in document order is adopted.
Replacing a target by inserting the new element before removing the old one therefore works, wherever the new one goes.
Elements that arrive in the same synchronous run of script while the property has no target are not kept waiting
behind each other: the first of them in document order becomes the target.
Doing both in one synchronous run of script reports nothing. If the first is still there after that, the second is a
mistake and is [reported like an uncaught error](/utilities/connected#errors). Use
[`@targets()`](#multiple-targets) when several elements share a name.
## Multiple targets
Multiple targets can be referenced via the `@targets()` decorator. Once the element has initialized, the property is
every matching element in document order, and an empty array while there are none — so it is safe to iterate. The same
array is returned until the targets change, so treat it as read-only: copy it before sorting or reversing it.
```html{2,3}
```
```ts{6}
// elements/greet_user_element.ts
import { ImpulseElement, registerElement, targets } from '@ambiki/impulse';
@registerElement('greet-user')
export default class GreetUserElement extends ImpulseElement {
@targets() results: HTMLElement[];
// ...
}
```
## How targets are resolved
A target is not a one-off `querySelector()`. Impulse watches the document, so the property follows the DOM — a target
that is replaced, moved, or rendered later is picked up without any work on your part, which is what makes the
[connected and disconnected callbacks](#connected-and-disconnected-callbacks) possible.
Reading the property reflects the DOM as it is now, even right after a target is appended or removed in the same
method:
```ts
addTag(text: string) {
this.append(this.renderTag(text));
// Includes the new tag's button.
for (const button of this.removeButtons) button.disabled = this.disabled;
}
```
The [connected and disconnected callbacks](#connected-and-disconnected-callbacks) still run when Impulse's
`MutationObserver` delivers the change, a moment after it is made, once the code that made it has finished. Until then,
the property can already hold an element whose connected callback has not run yet, or no longer hold one whose
disconnected callback has not run yet.
Inside a callback Impulse runs as it delivers changes, such as a `[target]Connected` or a
[`connected()`](/utilities/connected) callback, the property reflects the changes delivered so far.
While changes wait to be delivered, a read looks through the element's descendants for its targets and keeps the answer
until the DOM changes again. A loop that changes the DOM and reads the property on every pass repeats that search on
every pass, so read it once after the loop.
Moving the element itself tears it down and [initializes](/utilities/when-initialized) it again at its new place. In
between, the property still reads its targets from the DOM, and their disconnected and connected callbacks run with the
teardown and the new initialization.
A `data-target` token belongs to the closest ancestor (or the element itself) whose tag name matches the identifier in
the token. Nested elements of the same tag therefore never claim each other's targets:
```html{3,7}
```
## Connected and disconnected callbacks
Using the `@target()` or `@targets()` decorator lets you respond whenever a target element is connected or disconnected
from the DOM.
Define a `[target]Connected` or `[target]Disconnected` function, where `[target]` is the name of the target you want to
observe. The function receives the element as the first argument.
```ts{5,7,11}
import { ImpulseElement, registerElement, target } from '@ambiki/impulse';
@registerElement('greet-user')
export default class GreetUserElement extends ImpulseElement {
@target() result: HTMLElement;
resultConnected(result: HTMLElement) {
// result connected to the DOM.
}
resultDisconnected(result: HTMLElement) {
// result disconnected from the DOM.
}
}
```
## Naming conventions
Always use camelCase to reference the target in your HTML.
```html
```
```ts
import { ImpulseElement, registerElement, target } from '@ambiki/impulse';
@registerElement('greet-user')
export default class GreetUserElement extends ImpulseElement {
@target() doThis: HTMLElement;
}
```
---
---
url: 'https://ambiki.github.io/impulse/utilities/connected.md'
---
# connected
The `connected` function allows you to observe the DOM and invoke a callback whenever elements matching a selector are added to the DOM.
## Usage
This function sets up a [MutationObserver](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) on the
document that watches for elements matching the provided CSS selector. The callback is invoked for any matching
elements already in the DOM, then for any elements added later, and for any element whose attributes change such that
it starts matching the selector. Nothing is matched [before the document is parsed](#before-the-document-is-parsed).
This is particularly useful for initializing third-party libraries that require a manual initialization step on a given
element.
This example initializes Bootstrap's [tooltip](https://getbootstrap.com/docs/4.6/components/tooltips/#tooltipoptions)
library on any element matching the selector.
```ts
import { connected } from '@ambiki/impulse';
connected('[data-toggle="tooltip"]', (element) => {
$(element).tooltip();
// Destroy the tooltip instance when the element is removed from the page.
return () => {
$(element).tooltip('dispose');
};
});
```
## Cleanup
The callback can optionally return a cleanup function that will be called when the element is disconnected from the DOM. This is useful for removing event listeners or clearing timers.
```ts{4-6}
connected('.dynamic-content', (element) => {
console.log('Element connected: ', element);
return () => {
console.log('Element disconnected: ', element);
};
});
```
## Stopping observation
The `connected` function returns a cleanup function that stops observing when called. Any element still in the DOM at that point has its cleanup function run immediately, since it will never be disconnected through this watcher.
Every cleanup runs even if one throws. The first error is then thrown from `stop()`, not reported to `window.onerror`.
```ts{1,6}
const stop = connected('div', (element) => {
console.log('Connected');
});
// Later, stop observing
stop();
```
## Before the document is parsed
While the browser is still parsing the page (`document.readyState` is `loading`), an element is in the document before
its children are, so a callback could run on a half-built element. Impulse therefore matches nothing until the document
is parsed.
* Called during the parse — from a blocking `