Part 3 / Module context / Sharing code
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
:
AudioPlayer.svelte
<script context="module">
let current;
</script>
It's now possible for the components to 'talk' to each other without any state management:
AudioPlayer.svelte
function stopOthers() {
if (current && current !== audio) current.pause();
current = audio;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<script>
import AudioPlayer from './AudioPlayer.svelte';
</script>
<!-- https://musopen.org/music/9862-the-blue-danube-op-314/ -->
<AudioPlayer
src="https://learn.svelte.dev/assets/media/music/strauss.mp3"
title="The Blue Danube Waltz"
composer="Johann Strauss"
performer="European Archive"
/>
<!-- https://musopen.org/music/43775-the-planets-op-32/ -->
<AudioPlayer
src="https://learn.svelte.dev/assets/media/music/holst.mp3"
title="Mars, the Bringer of War"
composer="Gustav Holst"
performer="USAF Heritage of America Band"
/>
<!-- https://musopen.org/music/8010-3-gymnopedies/ -->
<AudioPlayer
src="https://learn.svelte.dev/assets/media/music/satie.mp3"
title="Gymnopédie no. 1"
composer="Erik Satie"
performer="Prodigal Procrastinator"
/>
<!-- https://musopen.org/music/2567-symphony-no-5-in-c-minor-op-67/ -->
<AudioPlayer
src="https://learn.svelte.dev/assets/media/music/beethoven.mp3"
title="Symphony no. 5 in Cm, Op. 67 - I. Allegro con brio"
composer="Ludwig van Beethoven"
performer="European Archive"
/>
<!-- https://musopen.org/music/43683-requiem-in-d-minor-k-626/ -->
<AudioPlayer
src="https://learn.svelte.dev/assets/media/music/mozart.mp3"
title="Requiem in D minor, K. 626 - III. Sequence - Lacrymosa"
composer="Wolfgang Amadeus Mozart"
performer="Markus Staab"
/>
initialising