Skip to content

get context of next customElement ancestor  #8

@Vanillabacke

Description

@Vanillabacke

Just wanna share a quick and dirty solution of getting the context kinda working.

Needs a new method in the wrapper class:

getAncestorContext( node = false )  {
    while ( node.parentNode ) {
        if ( node._root?.elem?.$$?.context  ) {
            return node._root?.elem?.$$?.context
        }
        node = node.parentNode
    }
    return false
}

And then adopt the context in the opts.component constructor:

connectedCallback(){
    let props = opts.defaults ? opts.defaults : {};

    // ...

    props.$$slots = createSlots(slots)
    this.elem = new opts.component({
        target: this._root,
        context: this.getAncestorContext(this?._root), // add the context to the component
        props
    });
}

Usage for example with a writable:
Parent:

<script>
import { setContext} from 'svelte';
import {writable} from 'svelte/store';

const yourName= writable('default name');
setContext('yourName',yourName);
</script>

<div>{$yourName}<div>

Child:

<script>
import { getContext } from 'svelte';
let yourName= getContext('yourName')

updateName(){
    $yourName = 'your new name';
}
</script>

<div>{$yourName}<div>
<button on:click={updateName}>Update the Name</button>

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions