Skip to content

Add ability for Custom Elements to emit events #8475

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
tronicboy1 opened this issue Apr 11, 2023 · 1 comment
Closed

Add ability for Custom Elements to emit events #8475

tronicboy1 opened this issue Apr 11, 2023 · 1 comment

Comments

@tronicboy1
Copy link

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

@dummdidumm
Copy link
Member

Duplicate of #3119

@dummdidumm dummdidumm marked this as a duplicate of #3119 Apr 11, 2023
@dummdidumm dummdidumm closed this as not planned Won't fix, can't repro, duplicate, stale Apr 11, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants