Skip to content

Build Elements / directive

directive ​

js
import {
  adopted,
  attributeChanged,
  connected,
  define,
  disconnected,
  execute,
  formAssociated,
  formDisabled,
  formReset,
  formStateRestore,
} from '@t2e1/kuba/directive'

Decorators over the native custom element lifecycle. Each one wraps a callback rather than replacing it, so several can hook the same callback and they chain. See Lifecycle for how they fit together.

define(name, options?) ​

Class decorator. Registers the class in the custom element registry, skipping registration when name already exists — so a module evaluated twice doesn't throw.

js
@define('my-counter')
class Counter extends HTMLElement {}
ParameterTypeDescription
namestringTag name. Must contain a hyphen, per the platform.
optionsElementDefinitionOptionsPassed through to customElements.define, e.g. { extends: 'button' }.

attributeChanged(attribute, ...filters) ​

Accessor decorator. Adds attribute to observedAttributes and syncs the decorated property from it on every attributeChangedCallback, passing the raw string through filters in order first.

js
@attributeChanged('count')
set count(value) { this.#count = Number(value) }

@attributeChanged('hidden', booleanAttribute)
set hidden(value) { this.#hidden = value }

The direction is attribute → property only. Setting the property does not write the attribute back.

Filters ​

Importable from @t2e1/kuba/directive/attributeChanged:

FilterTurns the raw value into
booleanAttributetrue when the attribute is present, false when removed
resizinga CSS length — numeric px/% values pass through, keywords are normalized

Lifecycle hooks ​

Method decorators. Each runs the decorated method after the corresponding native callback, receiving the same arguments.

DecoratorRuns after
connectedconnectedCallback
disconnecteddisconnectedCallback
adoptedadoptedCallback
formAssociatedformAssociatedCallback
formDisabledformDisabledCallback
formResetformResetCallback
formStateRestoreformStateRestoreCallback
js
@connected
[slottable]() {
  this.setAttribute('slot', 'helper')
  return this
}

Symbol-keyed methods are the convention here — they keep the hook off the public surface of the element. Each package defines its own in an interface.js.

execute(method) ​

The builder behind every hook above. Use it to write your own:

js
const ready = (target, method) =>
  execute(method).on(target).after('connectedCallback')
StepArgumentDescription
execute(method)string | symbolThe method to invoke on the instance.
.on(target)prototypeWhere to install the wrapper.
.after(event)stringName of the callback to wrap.

It proxies the existing callback instead of overwriting it, which is what makes hooks composable.