Skip to content

Commit 640d40b

Browse files
authored
Merge pull request #385 from mindrones/issue-373
Document event modifiers
2 parents 60d3a4a + a12f9e6 commit 640d40b

File tree

1 file changed

+46
-1
lines changed

1 file changed

+46
-1
lines changed

content/guide/07-element-directives.md

+46-1
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,51 @@ The target node can be referenced as `this`, meaning you can do this sort of thi
7676
<input on:focus="this.select()" value="click to select">
7777
```
7878

79+
### Event handler modifiers
80+
81+
While you can invoke methods like `event.stopPropagation` directly...
82+
83+
```html
84+
<!-- { repl: false } -->
85+
<div on:click="event.stopPropagation()">...</div>
86+
```
87+
88+
...it gets annoying if you want to combine that with some other behaviour:
89+
90+
```html
91+
<!-- { repl: false } -->
92+
<div on:click="setFoo(event)">...</div>
93+
94+
<script>
95+
export default {
96+
methods: {
97+
setFoo(event) {
98+
event.stopPropagation();
99+
event.preventDefault();
100+
this.set({ foo: true });
101+
}
102+
}
103+
};
104+
</script>
105+
```
106+
107+
For that reason, Svelte lets you use *event modifiers*:
108+
109+
- [`preventDefault`](https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
110+
- [`stopPropagation`](https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation)
111+
- [`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)
112+
- [`once`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Parameters) — removes the listener after the first invocation
113+
- [`capture`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Parameter)
114+
115+
> `passive` and `once` are not implemented in `legacy` mode
116+
117+
The example above can be achieved with modifiers — no need for a custom method:
118+
119+
```html
120+
<!-- { repl: false } -->
121+
<div on:click|stopPropagation|preventDefault="set({ foo: true })">...</div>
122+
```
123+
79124
### Custom events
80125

81126
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.
@@ -618,4 +663,4 @@ export default {
618663
"isSelected": false,
619664
"isAdmin": false,
620665
}
621-
```
666+
```

0 commit comments

Comments
 (0)