Skip to content

run onMount in connectedCallback for custom elements #4527

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
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions src/runtime/internal/Component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,9 @@ export function mount_component(component, target, anchor) {

fragment && fragment.m(target, anchor);

// custom element: call onMount in connectedCallback instead
if (component.shadowRoot) return;

// onMount happens before the initial afterUpdate
add_render_callback(() => {
const new_on_destroy = on_mount.map(run).filter(is_function);
Expand Down Expand Up @@ -176,6 +179,10 @@ if (typeof HTMLElement === 'function') {
// @ts-ignore todo: improve typings
this.appendChild(this.$$.slotted[key]);
}

const new_on_destroy = this.$$.on_mount.map(run).filter(is_function);
this.$$.on_destroy.push(...new_on_destroy);
// don't reset on_mount array as not to interfere with reinsertion
}

attributeChangedCallback(attr, _oldValue, newValue) {
Expand Down
3 changes: 3 additions & 0 deletions test/custom-elements/samples/oncreate/main.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,11 @@
import { onMount } from 'svelte';

export let wasCreated;
export let propsSetBeforeMount;
export let attrs;

onMount(() => {
wasCreated = true;
propsSetBeforeMount = attrs === 'should be set';
});
</script>
3 changes: 2 additions & 1 deletion test/custom-elements/samples/oncreate/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import * as assert from 'assert';
import './main.svelte';

export default function (target) {
target.innerHTML = '<my-app/>';
target.innerHTML = '<my-app attrs="should be set" />';
const el = target.querySelector('my-app');
assert.ok(el.wasCreated);
assert.ok(el.propsSetBeforeMount);
}