Svelte Svelte

Modules Context for Sharing Code

Check out a free preview of the full Svelte course:
The "Modules Context for Sharing Code" Lesson is part of the full, Svelte course featured in this preview video. Here's what you'd learn in this lesson:

Rich explains that in previous example the code executes once the component estentiates, and demonstrates how to create modules for running code for each modules rather than scoping code to the component.

Get Unlimited Access Now

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:45] [MUSIC]

[00:02:51] Like so.