Module context
In all the examples we've seen so far, the <script>
block contains code that runs when each component instance is initialised. For the vast majority of components, that's all you'll ever need.
Very occasionally, you'll need to run some code outside of an individual component instance. For example, you can play all five of these audio players simultaneously; it would be better if playing one stopped all the others.
We can do that by declaring a <script context="module">
block. Code contained inside it will run once, when the module first evaluates, rather than when a component is instantiated. Place this at the top of AudioPlayer.svelte
:
<script context="module">
let current;
</script>
It's now possible for the components to 'talk' to each other without any state management:
function stopOthers() {
if (current && current !== audio) current.pause();
current = audio;
}
App.svelte
AudioPlayer.svelte
xxxxxxxxxx
44
1
<script>
2
import AudioPlayer from './AudioPlayer.svelte';
3
</script>
4
5
<!-- https://musopen.org/music/9862-the-blue-danube-op-314/ -->
6
<AudioPlayer
7
src="https://sveltejs.github.io/assets/music/strauss.mp3"
8
title="The Blue Danube Waltz"
9
composer="Johann Strauss"
10
performer="European Archive"
11
/>
12
13
<!-- https://musopen.org/music/43775-the-planets-op-32/ -->
14
<AudioPlayer
15
src="https://sveltejs.github.io/assets/music/holst.mp3"
16
title="Mars, the Bringer of War"
17
composer="Gustav Holst"
18
performer="USAF Heritage of America Band"
19
/>
20
Console
xxxxxxxxxx
139
1
/* App.svelte generated by Svelte v3.23.2 */
2
import {
3
SvelteComponent,
4
create_component,
5
destroy_component,
6
detach,
7
init,
8
insert,
9
mount_component,
10
noop,
11
safe_not_equal,
12
space,
13
transition_in,
14
transition_out
15
} from "svelte/internal";
16
Compiler options
result = svelte.compile(source, {
generate:
});xxxxxxxxxx
1
1
/* Add a <style> tag to see compiled CSS */