Skip to content

docs: update component directives page #9040

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jul 28, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 27 additions & 4 deletions documentation/docs/02-template-syntax/06-component-directives.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,34 @@ title: Component directives
on:eventname={handler}
```

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:
Components can emit events using [`createEventDispatcher`](/docs/svelte#createeventdispatcher) or by forwarding DOM events.

```svelte
<!-- SomeComponent.svelte -->
<script>
import { createEventDispatcher } from 'svelte';

const dispatch = createEventDispatcher();
</script>

<!-- programmatic dispatching -->
<button on:click={() => dispatch('hello')}>
one
</button>

<!-- declarative event forwarding -->
<button on:click>
two
</button>
```

Listening for component events looks the same as listening for DOM events:

```svelte
<SomeComponent on:whatever={handler} />
```

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.
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.

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

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.

## bind:this

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

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

> Note that we can't do `{cart.empty}` since `cart` is `undefined` when the button is first rendered and throws an error.

```svelte
<ShoppingCart bind:this={cart} />

<button on:click={() => cart.empty()}> Empty shopping cart </button>
```

> Note that we can't do `{cart.empty}` since `cart` is `undefined` when the button is first rendered and throws an error.