Unlike DOM events, component events don't bubble. If you want to listen to an event on some deeply nested component, the intermediate components must forward the event.
In this case, we have the same App.svelte
and Inner.svelte
as in the previous chapter, but there's now an Outer.svelte
component that contains <Inner/>
.
One way we could solve the problem is adding createEventDispatcher
to Outer.svelte
, listening for the message
event, and creating a handler for it:
<script>
import Inner from './Inner.svelte';
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
function forward(event) {
dispatch('message', event.detail);
}
</script>
<Inner on:message={forward}/>
But that's a lot of code to write, so Svelte gives us an equivalent shorthand — an on:message
event directive without a value means 'forward all message
events'.
<script>
import Inner from './Inner.svelte';
</script>
<Inner on:message/>
App.svelte
Inner.svelte
Outer.svelte
xxxxxxxxxx
9
1
<script>
2
import Outer from './Outer.svelte';
3
4
function handleMessage(event) {
5
alert(event.detail.text);
6
}
7
</script>
8
9
<Outer on:message={handleMessage}/>
Console
xxxxxxxxxx
57
1
/* App.svelte generated by Svelte v3.23.2 */
2
import {
3
SvelteComponent,
4
create_component,
5
destroy_component,
6
init,
7
mount_component,
8
noop,
9
safe_not_equal,
10
transition_in,
11
transition_out
12
} from "svelte/internal";
13
14
import Outer from "./Outer.svelte";
15
16
function create_fragment(ctx) {
xxxxxxxxxx
57
1
/* App.svelte generated by Svelte v3.23.2 */
2
import {
3
SvelteComponent,
4
create_component,
5
destroy_component,
6
init,
7
mount_component,
8
noop,
9
safe_not_equal,
10
transition_in,
11
transition_out
12
} from "svelte/internal";
13
14
import Outer from "./Outer.svelte";
15
16
function create_fragment(ctx) {
Compiler options
result = svelte.compile(source, {
generate:
});xxxxxxxxxx
1
1
/* Add a <style> tag to see compiled CSS */
xxxxxxxxxx
1
1
/* Add a <style> tag to see compiled CSS */