Skip to content

Commit ce04765

Browse files
authored
docs: update component directives page (#9040)
1 parent d6abd0a commit ce04765

File tree

1 file changed

+27
-4
lines changed

1 file changed

+27
-4
lines changed

documentation/docs/02-template-syntax/06-component-directives.md

+27-4
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,34 @@ title: Component directives
88
on:eventname={handler}
99
```
1010

11-
Components can emit events using [createEventDispatcher](/docs/svelte#createeventdispatcher), or by forwarding DOM events. Listening for component events looks the same as listening for DOM events:
11+
Components can emit events using [`createEventDispatcher`](/docs/svelte#createeventdispatcher) or by forwarding DOM events.
12+
13+
```svelte
14+
<!-- SomeComponent.svelte -->
15+
<script>
16+
import { createEventDispatcher } from 'svelte';
17+
18+
const dispatch = createEventDispatcher();
19+
</script>
20+
21+
<!-- programmatic dispatching -->
22+
<button on:click={() => dispatch('hello')}>
23+
one
24+
</button>
25+
26+
<!-- declarative event forwarding -->
27+
<button on:click>
28+
two
29+
</button>
30+
```
31+
32+
Listening for component events looks the same as listening for DOM events:
1233

1334
```svelte
1435
<SomeComponent on:whatever={handler} />
1536
```
1637

17-
As with DOM events, if the `on:` directive is used without a value, the component will _forward_ the event, meaning that a consumer of the component can listen for it.
38+
As with DOM events, if the `on:` directive is used without a value, the event will be forwarded, meaning that a consumer can listen for it.
1839

1940
```svelte
2041
<SomeComponent on:whatever />
@@ -92,6 +113,8 @@ You can bind to component props using the same syntax as for elements.
92113
<Keypad bind:value={pin} />
93114
```
94115

116+
While Svelte props are reactive without binding, that reactivity only flows downward into the component by default. Using `bind:property` allows changes to the property from within the component to flow back up out of the component.
117+
95118
## bind:this
96119

97120
```svelte
@@ -100,10 +123,10 @@ bind:this={component_instance}
100123

101124
Components also support `bind:this`, allowing you to interact with component instances programmatically.
102125

103-
> Note that we can't do `{cart.empty}` since `cart` is `undefined` when the button is first rendered and throws an error.
104-
105126
```svelte
106127
<ShoppingCart bind:this={cart} />
107128
108129
<button on:click={() => cart.empty()}> Empty shopping cart </button>
109130
```
131+
132+
> Note that we can't do `{cart.empty}` since `cart` is `undefined` when the button is first rendered and throws an error.

0 commit comments

Comments
 (0)