Skip to content

Document event modifiers #385

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
Dec 15, 2018
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
47 changes: 46 additions & 1 deletion content/guide/07-element-directives.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,51 @@ The target node can be referenced as `this`, meaning you can do this sort of thi
<input on:focus="this.select()" value="click to select">
```

### Event handler modifiers

While you can invoke methods like `event.stopPropagation` directly...

```html
<!-- { repl: false } -->
<div on:click="event.stopPropagation()">...</div>
```

...it gets annoying if you want to combine that with some other behaviour:

```html
<!-- { repl: false } -->
<div on:click="setFoo(event)">...</div>

<script>
export default {
methods: {
setFoo(event) {
event.stopPropagation();
event.preventDefault();
this.set({ foo: true });
}
}
};
</script>
```

For that reason, Svelte lets you use *event modifiers*:

- [`preventDefault`](https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
- [`stopPropagation`](https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation)
- [`passive`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Parameters) — improves scrolling performance on touch/wheel events (Svelte will add it automatically where it's safe to do so)
- [`once`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Parameters) — removes the listener after the first invocation
- [`capture`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Parameter)

> `passive` and `once` are not implemented in `legacy` mode

The example above can be achieved with modifiers — no need for a custom method:

```html
<!-- { repl: false } -->
<div on:click|stopPropagation|preventDefault="set({ foo: true })">...</div>
```

### Custom events

You can define your own custom events to handle complex user interactions like dragging and swiping. See the earlier section on [custom event handlers](guide#custom-event-handlers) for more information.
Expand Down Expand Up @@ -618,4 +663,4 @@ export default {
"isSelected": false,
"isAdmin": false,
}
```
```