Skip to content

Add ability for Custom Elements to emit events  #8475

Closed as not planned
Closed as not planned
@tronicboy1

Description

@tronicboy1

Describe the problem

You cannot emit events in Svelte Web Components with the Svelte dispatcher.

Describe the proposed solution

I think adding an option in the dispatch callback to emit from the component if it extends an HTMLElement would be a possible solution.

src/runtime/internal/lifecycle.ts

export function createEventDispatcher<EventMap extends {} = any>(): <
	EventKey extends Extract<keyof EventMap, string>
>(
	type: EventKey,
	detail?: EventMap[EventKey],
	options?: DispatchOptions
) => boolean {
	const component = get_current_component();

	return (type: string, detail?: any, { cancelable = false, composed, bubbles } = {}): boolean => {
		const callbacks = component.$$.callbacks[type];
		const isCustomElement = component instanceof HTMLElement;

		if (callbacks || isCustomElement) {
			// TODO are there situations where events could be dispatched
			// in a server (non-DOM) environment?
			const event = custom_event(type, detail, { cancelable, composed, bubbles });
			callbacks.slice().forEach((fn) => {
				fn.call(component, event);
			});
			// dispatch from el if Custom Element
			if (isCustomElement) {
				component.dispatchEvent(event);
			}
			return !event.defaultPrevented;
		}

		return true;
	};
}

Alternatives considered

The workaround I use in my components is as follows.

export function createCustomElementEventDispatcher() {
    const component = /** @type {HTMLElement} */ (get_current_component());
    return (type, detail = undefined) => {
        const e = new CustomEvent(type, { composed: true, detail });
        component.dispatchEvent(e);
    };
}

Importance

would make my life easier

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions