[feat] get all contexts (#6528)

* get all contexts

* docs

* explicit return type

* allow specifying return type through generic parameter

* Update site/content/docs/03-run-time.md

Co-authored-by: Ben McCann <322311+benmccann@users.noreply.github.com>
Co-authored-by: Simon H <5968653+dummdidumm@users.noreply.github.com>
Co-authored-by: Ben McCann <322311+benmccann@users.noreply.github.com>
pull/6560/head
Tan Li Hau 3 years ago committed by GitHub
parent f6a9804275
commit 222a9dd2c6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -200,6 +200,24 @@ Checks whether a given `key` has been set in the context of a parent component.
</script>
```
#### `getAllContexts`
```js
contexts: Map<any, any> = getAllContexts()
```
---
Retrieves the whole context map that belongs to the closest parent component. Must be called during component initialisation. Useful, for example, if you programmatically create a component and want to pass the existing context to it.
```sv
<script>
import { getAllContexts } from 'svelte';
const contexts = getAllContexts();
</script>
```
#### `createEventDispatcher`
```js

@ -7,6 +7,7 @@ export {
afterUpdate,
setContext,
getContext,
getAllContexts,
hasContext,
tick,
createEventDispatcher,

@ -54,6 +54,10 @@ export function getContext<T>(key): T {
return get_current_component().$$.context.get(key);
}
export function getAllContexts<T extends Map<any, any> = Map<any, any>>(): T {
return get_current_component().$$.context;
}
export function hasContext(key): boolean {
return get_current_component().$$.context.has(key);
}

@ -1,6 +1,7 @@
export {
setContext,
getContext,
getAllContexts,
hasContext,
tick,
createEventDispatcher,

@ -0,0 +1,9 @@
<script>
import { getAllContexts } from 'svelte';
const context = getAllContexts();
</script>
{#each [...context.keys()] as key}
<div>{key}: {context.get(key)}</div>
{/each}

@ -0,0 +1,8 @@
<script>
import { setContext } from 'svelte';
setContext('a', 1);
setContext('b', 2);
setContext('c', 3);
</script>
<slot></slot>

@ -0,0 +1,7 @@
export default {
html: `
<div>a: 1</div>
<div>b: 2</div>
<div>c: 3</div>
`
};

@ -0,0 +1,8 @@
<script>
import Nested from './Nested.svelte';
import Leaf from './Leaf.svelte';
</script>
<Nested>
<Leaf />
</Nested>
Loading…
Cancel
Save