Skip to content

Support context from custom element ancestors #10

@patricknelson

Description

@patricknelson

Stub for an issue originally created by @Vanillabacke, see crisward/svelte-tag#8

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

Labels

enhancementNew feature or request

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions