Transcript from the "Modules Context for Sharing Code" Lesson
>> So in all of the example components that we've looked at so far, we've been running logic inside the script block, which means that it executes once the component instantiates. And that's useful for most of the things that we need to do, but occasionally, we need to have some logic that runs once for the entire module and is shared between all instances of the component.
[00:00:22] And for that, we have something called context = "module". So, in this app, we have a bunch of different audio elements. And if I start playing one of them and then start playing another one, they'll all play over each other, and that's no good. What we want is for each play to cause all of the other audio elements to stop playing.
[00:00:43] And so we'll do that by having some state that is shared between all of the audio players. We'll begin by creating a script with context = "module". And then we're just gonna have a single pieces state here called current. And then, in this function, stopOthers, whenever the audio element is played, We're just gonna see if this is the current audio, and if it's not, pause it.
[00:01:29] And change the value of current. So now if we play this piece of audio and then play this piece of audio, the first piece of audio will stop. Now anything that gets exported from a context = "module" script block becomes an export from the module itself. So if we export a stopAll function from AudioPlayer.svelte, like this, export function stopAll(), And then just take all of the elements in this set and pause it.
[00:02:26] We can now import that function into App.svelte, like this. And we can use it inside this button's event handler,
[00:02:51] Like so.