Radiant0.3.0-rc.2

createEvent

createEvent creates a type-safe EventEmitter bound to a host element and registers it on the host's internal emitter registry. It is the functional equivalent of the @event decorator.

Usage

import type { EventEmitter } from '@ecopages/radiant/tools/event-emitter';
import { RadiantElement } from '@ecopages/radiant';
import { createEvent } from '@ecopages/radiant/helpers/create-event';
import { createEventListener } from '@ecopages/radiant/helpers/create-event-listener';
 
class CounterButton extends RadiantElement {
	#countChanged: EventEmitter<{ count: number }>;
	#count = 0;
 
	constructor() {
		super();
		this.#countChanged = createEvent(this, {
			name: 'count-changed',
			bubbles: true,
			composed: true,
		});
 
		createEventListener(this, { selector: 'button', type: 'click' }, () => {
			this.#count++;
			this.#countChanged.emit({ count: this.#count });
		});
	}
}
 
customElements.define('counter-button', CounterButton);

Use it with authored light DOM:

<counter-button>
	<button type="button">Increment</button>
</counter-button>

Parameters

createEvent<T>(host, config) accepts:

ParameterTypeRequiredDescription
hostRadiantElementYesThe element that will dispatch events.
configEventEmitterConfigYesEvent configuration (see below).

EventEmitterConfig

FieldTypeRequiredDescription
namestringYesThe event name (e.g., 'value-changed').
bubblesbooleanNoWhether the event bubbles up the DOM. If omitted, CustomEvent uses its platform default of false.
composedbooleanNoWhether the event crosses shadow DOM boundaries. If omitted, CustomEvent uses its platform default of false.
cancelablebooleanNoWhether the event can be cancelled (default: false).

If parent elements should observe the event through bubbling or delegated listeners, set bubbles: true explicitly.

Return Value

Returns an EventEmitter<T> instance. Call .emit(detail) to dispatch a CustomEvent with the provided detail payload.

const emitter = createEvent<{ value: string }>(host, { name: 'change' });
emitter.emit({ value: 'hello' });

Listening to Emitted Events

Pair createEvent with createEventListener on a parent element.

import { RadiantElement } from '@ecopages/radiant';
import { createEventListener } from '@ecopages/radiant/helpers/create-event-listener';
 
class ParentComponent extends RadiantElement {
	constructor() {
		super();
		createEventListener(
			this,
			{ selector: 'counter-button', type: 'count-changed' },
			(event) => {
				const detail = (event as CustomEvent<{ count: number }>).detail;
				console.log('Count:', detail.count);
			},
		);
	}
}
 
customElements.define('parent-component', ParentComponent);

Use it with nested authored elements:

<parent-component>
	<counter-button>
		<button type="button">Increment</button>
	</counter-button>
</parent-component>

Learn More